【问题标题】:RXJS ANGULAR - Observable still called after takeWhile operator is resolvedRXJS ANGULAR - 解析 takeWhile 运算符后仍调用 Observable
【发布时间】:2022-01-01 05:01:18
【问题描述】:

我将数据存储在会话存储中,并有一个到期日期:

private saveSessionData<T>(key: string, value: T) {
    const item = {
      value: value,
      expiry: Date.now() + 10 * 60000 // 10 minutes from now
    }
    sessionStorage.setItem(key, JSON.stringify(item));
  }

我有另一个函数可以访问这些数据,如果我尝试访问的数据已过期,它将返回 null:

private async getSessionData<T>(key: string): Promise<T | null> {
    const itemStr = sessionStorage.getItem(key);
    const item = JSON.parse(itemStr);
    if (Date.now() > item.expiry) {
      console.log('CONSOLE NULL');
      await this.alertService('OBJ EXPIRED');
      return null;
    }
    return item.value;
  }

我像这样访问这些数据:

getMyObj$ (): Observable<MyObj| null> {
    return from(this.getSessionData<MyObj>(this._myObj))
      .pipe(
        takeWhile(myObj => myObj != null),
        tap(x => console.log('getting my Obj')
    );
  }

在我看来,我正在使用 |异步显示myObj 具有两种数据绑定:

<div *ngIf="!!(getMyObj$ | async) as obj">
  <div>{{ obj }}</div>
</div>

我的想法是,我的控制台会一次又一次地向我显示getting my Obj,直到过期日期过期,然后看到警告消息:OBJ EXPIRED 和控制台消息CONSOLE NULL 一次。 但目前,在getting my Obj 消息之后,我有无限的CONSOLE NULL 消息(这使我的浏览器崩溃)并且警报事件从未显示。

有人知道吗?我不知道是什么导致了这样的崩溃。

【问题讨论】:

  • 盲猜,试试takeWhile(myObj =&gt; !!myObj)。也许它是未定义的,但 undefinednull 不是一回事,所以尽管 myObj 未定义,但条件结果是正确的?值得一试
  • 不幸的是,我遇到了与takeWhile(myObj =&gt; !!myObj)相同的问题

标签: javascript angular typescript rxjs


【解决方案1】:

这可能是因为角度变化检测,导致它重复调用该方法并每次订阅一个新的 observable。相反,您应该创建一次 observable 并共享它:

this.getMyObj$ = 
  interval(1000).pipe(
    concatMap(() => this.getSessionData<MyObj>(this._myObj)),
    takeWhile(myObj => myObj != null),
    tap(x => console.log('getting my Obj'),
    shareReplay(1)
  );

【讨论】:

  • 谢谢,间隔就是答案!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-18
  • 1970-01-01
  • 2021-03-27
  • 1970-01-01
  • 2018-10-08
  • 1970-01-01
相关资源
最近更新 更多