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

Mar*_*kus 9 javascript observable redux angular

  • 我有一个使用两个后卫的Angular设置.canLoadcanActivate
  • 两者都从@ angular-redux/store via获得相同的observable @select

问题:为什么在从那时起打破所有路由的同时canActivate使用@select返回的observable 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
  }

}
Run Code Online (Sandbox Code Playgroud)

APP-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: '/'
  }
];
Run Code Online (Sandbox Code Playgroud)

小智 -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;
  }
}
Run Code Online (Sandbox Code Playgroud)