Angular多个可观察守卫无法按顺序运行问题。
创始人
2024-10-24 16:01:16
0

该问题可以通过使用'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 | Promise | boolean {

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 | Promise | boolean { return this.canActivate(childRoute, state); }

private guard1(): Observable { // return observable1 }

private guard2(): Observable { // return observable2 }

private guard3(): Observable { // return observable3 }

}

在上面的代码中,我们将guard1、guard2和guard3合并成一个可观察对象,然后使用'switchMap”操作符将其转换为一个新的可观察对象。在新的可观察对象中,我们通过按照顺序检查守卫的返回值来确保它们按顺序执行。如果有任何守卫的返回值为'false”,则返回一个值为false的新的可观察对象,否则返回一个值为true的新的可观察对象。最后,我们可以在路由定义中使用该守卫。

相关内容

热门资讯

透视线上!wepoker脚本下... 透视线上!wepoker脚本下载,hhpoker德州挂真的有吗,透明挂教程(素来真的是有挂);原来确...
透视计算!aapoker透视软... 透视计算!aapoker透视软件,德州机器人代打脚本,技巧教程(起初真的是有挂);超受欢迎的aapo...
透视攻略!hhpoker透视脚... 透视攻略!hhpoker透视脚本安卓,wepoker软件靠谱么,解密教程(固有真的是有挂)1、这是跨...
透视app!wepoker透视... 透视app!wepoker透视脚本,wpk插件辅助,第三方教程(从来真的是有挂);1.wepoker...
透视好友房!wpk辅助购买,w... 透视好友房!wpk辅助购买,wepoker软件靠谱么,曝光教程(原本是有挂);wpk透视辅助官方版是...
透视脚本!wepoker底牌透... 透视脚本!wepoker底牌透视脚本app,pokerworld破解版下载,揭秘攻略(都是存在有挂)...
透视透视!wepoker透视脚... 透视透视!wepoker透视脚本免费,we poker辅助器下载,辅助教程(先前是真的有挂);科技安...
透视系统!hhpoker辅助下... 透视系统!hhpoker辅助下载,hhpoker是真的假的,解密教程(好像真的有挂);hhpoker...
透视工具!wepoker透视脚... 透视工具!wepoker透视脚本,竞技联盟透视插件,科技教程(好像是有挂)需要回顾用户提供的搜索结果...
透视规律!aapoker透视插... 透视规律!aapoker透视插件,sohoo poker辅助,总结教程(本来真的有挂);支持多人共享...