Before each request, I want to be sure that there is a user profile. For this, I use canActivateChild protection.
According to angular2 documentation, you can return the observable: https://angular.io/api/router/CanActivateChild
app.routes.ts
export const routes: Routes = [
{
path: '',
canActivateChild: [ProfileGuard],
children: [
{
path: 'home',
component: HomeComponent,
canActivate: [AuthGuard]
},
{
path: 'login',
component: LoginComponent,
canActivate: [GuestGuard]
},
}
];
canActivatedChild runs before the child route canActivate
profile.guard.ts:
export class ProfileGuard implements CanActivateChild {
constructor(private profileService: ProfileService, private snackbar: MdSnackBar) { }
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> {
if (this.profileService.user == null && localStorage.getItem('__token') != null) {
return this.profileService.loadProfile().map((user) => {
console.log('profile loaded');
this.profileService.user = <UserModel>user.data;
return true;
});
}
return true;
}
}
Load Profile Function:
public loadProfile(): Observable<any> {
console.log('load');
return this.http.get('/profile').map(res => res.json());
}
When I navigate the menu ( <a>s routeLink), it works console.log('profile loaded'). But if I reload the page using f5 or through the browser, it will never get there.
In progress console.log('load').
EDIT
If I canActivateChildcome back:
return Observable.of(true).map(() => {
console.log('Test');
return true;
});
It works great ... I get console.log('test')