簡體   English   中英

為什么在@ angular / redux-store中使用@select時,Angular Guard的行為會有所不同

[英]Why do Angular guards behave differently when using @select from @angular/redux-store

  • 我有一個使用兩個防護裝置的Angular裝置。 canLoadcanActivate
  • 兩者都通過@select從@ angular-redux / store獲得了相同的可觀察@select

問題 :為什么canActivate可以與@select返回的可觀察值canActivate工作,而canLoad中斷了所有路由? 兩名警衛有什么區別?

相關角度問題: https : //github.com/angular/angular/issues/18991

認證衛士

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

}

應用程序路由模塊

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: '/'
  }
];

我遇到了同樣的問題,因此要解決此問題並讓它同時在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$; 
  }

}

我遇到了同樣的問題,但我確實認為這是一個有角度的錯誤。 我最終只是重寫了我的后衛,以存儲通過訂閱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;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM