首页 > 解决方案 > 我想从承诺值中获取价值,然后返回 canActive 布尔值

问题描述

我试图从值中评估将路由器保护与路径一起使用的值

我尝试使用从承诺中获取值到canActivate()路由器保护中。

private routeURL = new Subject<string> ();

canActivate() {
    if (this.authenticationService.currentUserValue) {
        this.getNavigationEnd().then(res => console.log('2 ' + res) );
// I want to get this.getNavigationEnd()'s result[true or false] for router guard's canActivate().

        return true;
    }
    this.router.navigate(['/401']);
    return false;
  }

  async getNavigationEnd() {
    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd)
    ).subscribe((result) => {
      let value: any;
      value = result;
      this.routeURL.next(value.url);
    });
    const valueArray = this.routeURL.asObservable();
    let bool = false;
    await valueArray.subscribe(value => {
      console.log(value);
      if (this.menuURIarray.includes(value)) {
        bool = true;
      } else {
        bool = false;
      }
    });
    console.log('1 ' + bool);
    return bool;
  }

如果可以从带有值的 promise 中获取,则路由器守卫可以使用路由器路径检查路径。

this.menuURIarray是菜单列表数组。它与路由器的 navigationEnd 路径进行比较。

然后如果这个数组和navigationEnd不一样,就返回true或者false。

然后 canActivate 使用它进行检查。这是我的路由器保护方案

标签: angularrxjs

解决方案


canActivate可以同时返回boolean, Promise<boolean>, Observable<boolean>. 在您的情况下canActivate,可以只返回一个ObservablePromise

此示例过滤NavigationEnd并返回true

canActivate() {
    return this.router.events.pipe(
      filter(event => event instanceof NavigationEnd),
      map((event: NavigationEnd) => true),
    )
  }

文档:canActivate


推荐阅读