该问题可以通过使用'switchMap”操作符解决。首先,我们需要将多个守卫合并成一个可观察对象。然后使用'switchMap”操作符将守卫中的每个可观察对象转换为一个新的可观察对象,以确保它们被按顺序执行。最后,我们需要在守卫之间传递状态以便按顺序执行。
以下是具体的示例代码:
import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import { switchMap } from 'rxjs/operators/switchMap'; import { merge } from 'rxjs/observable/merge';
@Injectable() export class MultipleObservableGuard implements CanActivate, CanActivateChild {
constructor() { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable
const guard1 = this.guard1();
const guard2 = this.guard2();
const guard3 = this.guard3();
return merge(guard1, guard2, guard3).pipe(
switchMap(result => {
if (result === false) {
return Observable.of(false);
}
return Observable.of(true);
})
);
}
canActivateChild(
childRoute: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable
private guard1(): Observable
private guard2(): Observable
private guard3(): Observable
}
在上面的代码中,我们将guard1、guard2和guard3合并成一个可观察对象,然后使用'switchMap”操作符将其转换为一个新的可观察对象。在新的可观察对象中,我们通过按照顺序检查守卫的返回值来确保它们按顺序执行。如果有任何守卫的返回值为'false”,则返回一个值为false的新的可观察对象,否则返回一个值为true的新的可观察对象。最后,我们可以在路由定义中使用该守卫。
上一篇:Angular多个监视器