【问题标题】:How to return a value after `retryWhen` expires? (for `canActivate` guard)`retryWhen`过期后如何返回值? (对于 `canActivate` 守卫)
【发布时间】:2021-11-21 07:59:50
【问题描述】:

当我重新加载我的页面时,它总是转到空白页面而不是同一页面。这背后的原因是一旦用户刷新页面就会调用 canActivate 方法,该方法正在检查用户的权限,并且无法立即获取用户数据。用户数据会在几秒钟后出现。

我发现我可以在订阅中使用retryWhen,所以调用会重试3次,如果没有完成,我可以调用navigateToNoAccessArea()函数。

功能如下:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):         
     Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree 
  {
    return this.getUserData(route);
   
  }
  private getUserData(route: ActivatedRouteSnapshot): Observable<boolean> {
    return this.userService.getUserData()
      .pipe(
        map(userData => {
          // If userData is empty, it returns an error (and catched in retryWhen)
          if(userData === null) throw new Error('User Data not initialized');
          return userData;
        }),
        // when no data is present, it retries the subscription (up to 3 times)
        retryWhen(err => err.pipe(delay(1000), take(3),
          finalize(()=> {
          //   this is called after it fails 3 times
          //   return does not work
            this.navigateToNoAccessArea();
            return false;
          })
        )),
        map(userData=> {
          // this map is called when data is got (if the retry fails 3 times it is skipped)
          // ***Some data manipulation is done here and true or false is returned ***
        }),
      )
  }

如果重试失败 3 次,我应该以某种方式返回 false(因此 canActivate() 不会与 EmptyErrorImpl {message: 'no elements in sequence', name: 'EmptyError'} 出错。重定向到无访问区域的工作正常。

【问题讨论】:

    标签: angular typescript rxjs angular-ui-router canactivate


    【解决方案1】:

    试试这个:

    retryWhen(err =>{ 
    let flag = true;
    err.pipe(delay(1000), take(3),
              finalize(()=> {
              //   this is called after it fails 3 times
              //   return does not work
                this.navigateToNoAccessArea();
                flag=false;
              });
    return flag;
            )),
    

    【讨论】:

      猜你喜欢
      • 2017-07-26
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多