【问题标题】:Route guard doesn't work with 2 observableRoute Guard 不适用于 2 observable
【发布时间】:2019-09-22 19:05:41
【问题描述】:

我写了route guard,如下图。但是在 else 语句中,这永远不会返回结果。但它有一个结果。而且也没有错误。 this.hotelSettingsService.get().pipe(map(res => { if (res) {

如果我删除此 from(this.localStorageService.get(LocalStorage.SCROLL_VIEW_HOLDER)).pipe(map(path 部分,它会起作用。

我认为我做了一些根本错误的事情。有什么线索吗?

有关此行为的视频: Video

 canActivate(): Observable<boolean> {

    return from(this.localStorageService.get(LocalStorage.SCROLL_VIEW_HOLDER)).pipe(map(path => {
      if (path) {
        this.router.navigate(path);
        return true;
      } else {
        this.hotelSettingsService.get().pipe(map(res => {
          if (res) { // not come to here
            this.router.navigate([this.getLandingPage(environment.hotelName)]);
            return true;
          }
        }), catchError((err) => {
          return of(false);
        }));
      }
    }), catchError((err) => {
      return of(false);
    }));
  }

当我输入return:

这工作正常:

canActivate(): Observable<boolean> {

        return this.hotelSettingsService.get().pipe(map(res => {
              if (res) { 
                this.router.navigate([this.getLandingPage(environment.hotelName)]);
                return true;
              }
            }), catchError((err) => {
              return of(false);
            }));
          }
     }

【问题讨论】:

  • 如果返回 of(true) 会发生什么?
  • 如果没有返回,当你落在else上时,外部map内不会返回任何值
  • 返回后,您的 IDE 正确爆炸
  • @Jota.Toledo 不知道你在说什么?你能用代码提出你的建议吗?
  • @EhsanKiani 没有区别。您可以查看This is working fine: 部分。 return true; 工作正常

标签: angular typescript rxjs angular7 ionic4


【解决方案1】:

首先,您需要在this.hotelService.... 前面添加return,就像您在图像中添加的一样。然后你需要使用switchMap而不是map来展平结果:

 canActivate(): Observable<boolean> {
    // since we have (possibly) an inner observable, flatten the result
    return from(...).pipe(switchMap(path => {
      if (path) {
        this.router.navigate(path);
        // return observable of
        return of(true);
      } else {
        return this.hotelSettingsService.get().pipe(map(res => {
          if (res) {
            this.router.navigate([this.getLandingPage(environment.hotelName)]);
            return true;
          }
        }), catchError((err) => {
          return of(false);
        }));
      }
    }), catchError((err) => {
      return of(false);
    }));
  }

【讨论】:

    猜你喜欢
    • 2017-07-16
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    相关资源
    最近更新 更多