You can pre-fetch your data by using Resolvers in Angular2+, Resolvers process your data before your Component fully be loaded.
There are many cases that you want to load your component only if there is certain thing happening, for example navigate to Dashboard only if the person already logged in, in this case Resolvers are so handy.
Look at the simple diagram I created for you for one of the way you can use the resolver to send the data to your component.
Applying Resolver to your code is pretty simple, I created the snippets for you to see how the Resolver can be created:
import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { MyData, MyService } from './my.service';
@Injectable()
export class MyResolver implements Resolve<MyData> {
constructor(private ms: MyService, private router: Router) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<MyData> {
let id = route.params['id'];
return this.ms.getId(id).then(data => {
if (data) {
return data;
} else {
this.router.navigate(['/login']);
return;
}
});
}
}
and in the module:
import { MyResolver } from './my-resolver.service';
@NgModule({
imports: [
RouterModule.forChild(myRoutes)
],
exports: [
RouterModule
],
providers: [
MyResolver
]
})
export class MyModule { }
and you can access it in your Component like this:
/////
ngOnInit() {
this.route.data
.subscribe((data: { mydata: myData }) => {
this.id = data.mydata.id;
});
}
/////
And in the Route something like this (usually in the app.routing.ts file):
////
{path: 'yourpath/:id', component: YourComponent, resolve: { myData: MyResolver}}
////