What is the difference between using a resolver and simply fetching data inside a component's ngOnInit method?
Short answer
Fetching data inside ngOnInit means the component renders first, often showing a brief loading state, before the data actually arrives.
Advertisement
AModel answer
Fetching data inside ngOnInit means the component renders first, often showing a brief loading state, before the data actually arrives. A resolver instead delays the route's navigation until the data has already been fetched, so the component appears fully populated with data from the very first moment it renders.
// ngOnInit approach, briefly shows a loading state
ngOnInit() {
this.userService.getUser(this.id).subscribe((user) => this.user = user);
}
// Resolver approach, data is already available when the component renders
this.route.data.subscribe((data) => this.user = data['user']);Real-world example
A product detail page chooses to use a resolver specifically because showing a flash of empty content before the product details load in would feel jarring and unprofessional to shoppers browsing quickly.
Likely follow-ups
- Are there downsides to using a resolver, such as delaying the entire navigation while data loads?
- When might showing a quick loading state inside the component actually be the better user experience?
Related topics