angular2 guard not working on page refresh

时间秒杀一切 提交于 2019-12-05 02:00:10

问题


Before every request I want to be sure that there is a user profile available. I use a canActivateChild guard to do this.

According to the documentation of angular2 it is possible to return an 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]
      },
 }
];

The canActivatedChild is executed 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 through the menu (<a> with routeLink) the console.log('profile loaded') works. But if I reload the page with f5 or through the browser, it never gets there..

The console.log('load') is always executed.

EDIT:

If I in canActivateChild return:

return Observable.of(true).map(() => {
  console.log('Test');
  return true;
});

It works fine... I get the console.log('test')


回答1:


I think it's resolving before you get a response, try adding in a replay subject that resolves to true or false once your request returns

import {Observable, ReplaySubject} from 'rxjs/Rx';

public loadProfile(): Observable<any> {
  console.log('loading profile');
  return this.http.get('/profile').map(res => res.json());
}

public isUserLoggedInObs(): Observable<boolean> {
  const userLoggedIn: ReplaySubject<boolean> = new ReplaySubject<boolean>;
  this.loadProfile.first().subscribe(
     user => userLoggedIn.next(user.loggedIn === true)
  )
  return userLoggedIn.asObservable();
}


canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean>  {
   return this.profileService.isUserLoggedInObs()
}



回答2:


I was running on a RC of @angular/router. After i updated this it worked like expected.



来源:https://stackoverflow.com/questions/45255745/angular2-guard-not-working-on-page-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!