守卫返回Observable后取消Angular 5导航

时间:2018-04-27 09:20:39

标签: angular observable angular5 ngrx ngrx-store

我有三条路线,其中一条路线受到保护

app.routing-module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './modules/auth/login/login.component';
import { DashboardComponent } from './modules/dashboard/dashboard.component';
import { CustomersComponent } from './modules/customers/customers.component';

import { AuthGuard } from './shared/guards/auth.guard';


const routes: Routes = [
  {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full'
  },
  { path: 'home', component: DashboardComponent, canActivate: [AuthGuard] },
  { path: 'login', component: LoginComponent },
  { path: 'customers', component: CustomersComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [AuthGuard]
})
export class AppRoutingModule { }

如果用户从ngrx商店获得身份验证并且返回一个Observable以允许或不激活路径,那么警卫会获取

import { Injectable } from '@angular/core';
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  Router
} from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { catchError, map, switchMap, filter, take } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
import { Store } from '@ngrx/store';

import { getUserAuth } from '../../store/reducers';


@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private store: Store<any>, private router: Router) { }

  getUserAuth(): Observable<any> {
    return this.store.select(getUserAuth).pipe(
      filter((data: any) => data),
      take(1)
    );
  }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    return this.getUserAuth().pipe(
      switchMap(() => of(true)),
      catchError(() => of(false))
    );
  }
}

当在两条“公共”路线之间切换时,导航工作正常,但一旦尝试访问受保护的路线并被取消(用户不是身份验证),导航将被取消,并且不能接收任何路线。另一方面,如果用户被记录,导航工作正常,并且可以访问三条路线。

如果我在canActivate方法中返回一个简单的Observable.of(false),则无法接收受保护的路由,但导航到其他路由仍然有效

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
    return Observable.of(false);
}

为什么取消导航?

修改

我忘了说我正在使用@ ngrx / router-store所以我的app.module看起来像:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AppRoutingModule,
    CoreModule,
    StoreModule.forRoot(rootReducers, {metaReducers}),
    StoreRouterConnectingModule.forRoot({
      stateKey: 'router' // name of reducer key
    }),
    StoreDevtoolsModule.instrument({ maxAge: 25 }),
    EffectsModule.forRoot(rootEffects),
    AuthModule,
    DashboardModule,
    CustomersModule
  ],
  providers: [{ provide: RouterStateSerializer, useClass: CustomSerializer }],
  bootstrap: [AppComponent]
})

1 个答案:

答案 0 :(得分:2)

问题在于:

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private store: Store<any>, private router: Router) { }

  getUserAuth(): Observable<any> {
    return this.store.select(getUserAuth).pipe(
      filter((data: any) => data),
      ^^^^^^
      take(1)
    );
  }

AuthGuard会暂停导航,直到Observable解析为truefalse。由于您要过滤任何falsy null值,因此Observable在用户未经过身份验证时不会发出任何内容。您应该将值映射到true / false,而不是:

return this.store.select(getUserAuth).pipe(
  map((data: any) => !!data),
  ^^^^^^^^^^^^^^^^^^^^^^^^^
  take(1)
);