当使用@ angular / redux-store中的@select时,为什么Angular防护的行为会有所不同

时间:2017-09-04 16:15:22

标签: javascript angular redux observable

  • 我有一个使用两个后卫的Angular设置。 canLoadcanActivate
  • 通过@select
  • 从@ angular-redux / store获取相同的observable

问题:为什么canActivate使用@select返回canLoad从那时起打破所有路由的观察点?这两名警卫有什么区别?

相关角度问题:https://github.com/angular/angular/issues/18991

auth.guard.ts

@Injectable()
export class AuthGuard implements CanLoad, CanActivate {

  @select() readonly authenticated$: Observable<boolean>; // @angular-redux/store

  canLoad(): Observable<boolean> | boolean {
    // return true; // works
    return this.authenticated$; // ERROR: all routing stops from and to the current page
  }

  canActivate(): Observable<boolean> | boolean {
    // return true; // works
    return this.authenticated$; // works
  }

}

应用-routing.module

const routes: Routes = [
  {
    path: '',
    component: SomeAComponent,
    pathMatch: 'full'
  },
  {
    path: 'someb',
    component: SomeBComponent,
    canActivate: [
      AuthGuard
    ],
  },
  {
    path: 'lazy',
    loadChildren: './lazy/lazy.module#LazyModule',
    canLoad: [
      AuthGuard
    ]
  },
  {
    path: '**',
    redirectTo: '/'
  }
];

2 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,因此要解决该问题并使它在CanLoad和CanActivate中都可以工作,则应添加运算符take(1)

@Injectable()
export class AuthGuard implements CanLoad, CanActivate {

  @select() readonly authenticated$: Observable<boolean>; // @angular-redux/store

  canLoad(): Observable<boolean> | boolean {
    // return true; // works
    return this.authenticated$.pipe(take(1));
  }

  canActivate(): Observable<boolean> | boolean {
    // return true; // works
    return this.authenticated$; 
  }

}

答案 1 :(得分:-1)

我刚遇到同样的问题,我认为这是一个有角度的错误。我最后只是重写我的守卫来存储一个局部变量,该变量通过订阅Observable来填充。我在这里使用ngrx / store。

@Injectable()
export class MustBeAuthenticatedGuard implements CanActivate, CanLoad {

  constructor(private store: Store<fromAuth.State>) {
    store.select(fromAuth.authenticated)
      .subscribe((authenticated) => {
        this.authenticated = authenticated;
      });
  }

  private authenticated: boolean

  canLoad(): boolean {
    return this.isAuthenticated();
  }

  canActivate(): boolean {
    return this.isAuthenticated();
  }

  private isAuthenticated() {
    if (!this.authenticated) {
      this.store.dispatch(new SignIn());
    }
    return this.authenticated;
  }
}