Say I have a ValuesComponent that displays an array of Value in an HTML table.
// in value.ts export class Value { ... } // in values.component.ts @Component(...) export class ValuesComponent { ... } Being a good programmer and all, I've created a different class that is responsible for providing values. Let's call it the ValuesService.
// in values.service.ts @Injectable() export class ValuesService { public getValues(): Observable<Value[]> { ... } } Suppose that the service gets its values from a web service: /api/values
Now instead of injecting the service directly into my component, I want to let the Angular router pre-fetch the values before navigating to the component.
For that, I created a Resolve service class and plugged it into the router module.
// in values-resolver.service.ts export class ValuesResolverService implements Resolve<Value[]> { constructor(private backend: ValuesService) { } public resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Value[]> { return this.backend.getValues(); } } // In app.module.ts (in @NgModule()) imports: [ RouterModule.forRoot([{ path: 'values', component: ValuesComponent, resolve: { values: ValuesResolverService } }]) ] // In values.component.ts public values: Value[]; constructor(private route: ActivatedRoute) { } ngOnInit() { this.values = route.data.values as Value[]; } How am I doing so far? Good? Then where do I put my error handling for when ValuesService.getValues() fails? (connection error, internal server error, ...)
When a user tries to navigate to the /#/values route and an error occurs, I want to log the error to the console and stop navigation. Ideally, I'd like to redirect the user to the /#/error route (not shown in the example code).
console.logis fine. I just need to know where to put it and what to return (if anything).return this.backend.getValues().catch(...).Promise, anObservableor some other monadic abstraction from the resolver instead of the array of values itself. That way you can attach error handling inside the resolver and, by injecting the router into it as well, you can trigger navigation in.catch. Actually, it looks like you are returning anObservable<Value[]>so you can attach error handling in the call toValuesServiceand then redirect in the catch block. I think this will work.