Angular 5 次导航在守卫后取消 returns 可观察
Angular 5 navigation cancelled after guard returns Observable
我有3条路线,其中一条有守卫保护
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 存储的授权并且 return 是一个允许或不允许激活路由的 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))
);
}
}
当在两个 "public" 路线之间切换时,导航工作正常,但是一旦尝试访问受保护的路线并被取消(用户未授权),导航被取消并且 none的路线可以访问。另一方面,如果用户已登录,则导航工作正常并且可以访问三个路线。
如果我在canActivate方法中return一个简单的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]
})
问题出在这里:
@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
解析为 true
或 false
。由于您要过滤任何 falsy null
值,因此当用户未通过身份验证时,Observable
不会发出任何内容。您应该将值映射到 true
/ false
而不是:
return this.store.select(getUserAuth).pipe(
map((data: any) => !!data),
^^^^^^^^^^^^^^^^^^^^^^^^^
take(1)
);
我有3条路线,其中一条有守卫保护
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 存储的授权并且 return 是一个允许或不允许激活路由的 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))
);
}
}
当在两个 "public" 路线之间切换时,导航工作正常,但是一旦尝试访问受保护的路线并被取消(用户未授权),导航被取消并且 none的路线可以访问。另一方面,如果用户已登录,则导航工作正常并且可以访问三个路线。
如果我在canActivate方法中return一个简单的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]
})
问题出在这里:
@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
解析为 true
或 false
。由于您要过滤任何 falsy null
值,因此当用户未通过身份验证时,Observable
不会发出任何内容。您应该将值映射到 true
/ false
而不是:
return this.store.select(getUserAuth).pipe(
map((data: any) => !!data),
^^^^^^^^^^^^^^^^^^^^^^^^^
take(1)
);