angular2 守卫不工作在页面刷新 [英] angular2 guard not working on page refresh

查看:28
本文介绍了angular2 守卫不工作在页面刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在每次请求之前,我想确保有一个可用的用户配置文件.我使用 canActivateChild 守卫来做到这一点.

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

根据 angular2 的文档,可以返回一个 observable:https://angular.io/api/router/CanActivateChild

According to the documentation of angular2 it is possible to return an observable: https://angular.io/api/router/CanActivateChild

app.routes.ts

app.routes.ts

export const routes: Routes = [
  {
    path: '',
    canActivateChild: [ProfileGuard],
    children: [
      {
        path: 'home',
        component: HomeComponent,
        canActivate: [AuthGuard]
      },
      {
        path: 'login',
        component: LoginComponent,
        canActivate: [GuestGuard]
      },
 }
];

canActivatedChild在子路由canActivate

profile.guard.ts:

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;
  }

}

负载配置文件功能:

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

当我浏览菜单(routeLink)时,console.log('profile loaded') 工作.但是如果我用 f5 或通过浏览器重新加载页面,它永远不会到达那里..

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..

console.log('load') 总是被执行.

编辑:

如果我在canActivateChild中返回:

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

它工作正常......我得到了 console.log('test')

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

推荐答案

我在 @angular/router 的 RC 上运行.在我更新后,它按预期工作.

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

这篇关于angular2 守卫不工作在页面刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆