Imagine a scenario where you have a DataComponent
, which showcases an array of Data
in an HTML table.
// data.ts
export class Data { ... }
// data.component.ts
@Component(...)
export class DataComponent { ... }
To follow good programming practices, you decide to create a separate class responsible for providing the data. Let's call it DataService
.
// data.service.ts
@Injectable()
export class DataService {
public getData(): Observable<Data[]> {
...
}
}
Assume that the service retrieves its data from a web service: /api/data
Instead of directly injecting the service into your component, you opt to preload the data using Angular router before navigating to the component.
To achieve this, you introduce a Resolver
service class and integrate it with the router module.
// data-resolver.service.ts
export class DataResolverService implements Resolve<Data[]> {
constructor(private backend: DataService) {
}
public resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Data[]> {
return this.backend.getData();
}
}
// In app.module.ts (inside @NgModule())
imports: [
RouterModule.forRoot([{
path: 'data',
component: DataComponent,
resolve: { data: DataResolverService }
}])
]
// In data.component.ts
public data: Data[];
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
this.data = route.data.data as Data[];
}
Now, considering where to implement error handling when DataService.getData()
encounters an issue (like connection errors or internal server errors).
If a user attempts to visit the /#/data
route and an error occurs, you want to log the error, halt navigation, and ideally redirect them to the /#/error
route (not included in the sample code).