Reputation: 105
I am newbie in Angular 2. On Angular.io Routing tutorial, I see that ActivatedRouteSnapShot and RouterStateSnapshot always be declared(inject) in AuthGuard function: canActivate, canActivateChild, resolve .... However, usually just 1 be used. You can see below:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let url: string = state.url;
return this.checkLogin(url);
}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<Crisis> {
let id = route.params['id'];
return this.cs.getCrisis(id).then(crisis => {
if (crisis) {
return crisis;
} else { // id not found
this.router.navigate(['/crisis-center']);
return null;
}
});
}
So why do always need to inject both?
Upvotes: 4
Views: 4080
Reputation: 2046
The canActivate
method has these parameters because you implement the CanActivate Interface, which is a so called Guard.
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean;
So independently from the fact whether you need it or not, you have it, they will be provided by Angular when it calls the method.
For the resolve
method, the situation is the same, you implement the Resolve Interface, where you have to implement the resolve method:
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<T> | Promise<T> | T;
An interface is a contract and therefore non-negotiable.
Upvotes: 4