【问题标题】:rxjs pipe tap/map is not triggered when subscribe订阅时不触发 rxjs 管道点击/映射
【发布时间】:2020-03-10 21:05:41
【问题描述】:

我不知道为什么,但是当我将 Observable 与扩展方法和管道一起使用时,管道映射或点击没有触发。

import { Observable, Subscriber, Observer } from 'rxjs';
import { tap, map } from 'rxjs/operators';
...
declare module 'rxjs' {
    interface Observable<T> {
        useCache<T>(this: Observable<T>, key: string): Observable<T>;
    }
}
Observable.prototype.useCache = function<T>(this: Observable<T>, key: string) {
    // executed
    const inCache = LocalStorage.get(key);
    if (inCache) {
        return new Observable<T>(observer => observer.next(inCache));
    }
    // this.pipe(tap((e: T) => {
    //     LocalStorage.set(key, e);
    // }));

    this.pipe(map((e: T) => {
        //not executed
        LocalStorage.set(key, e);
    }));
    return this;
};
...
(in somewhere component)
this.service.get(...).subscribe(e=>{
    //executed!
});

在其他任何地方,我都可以设置停在那里但不在 map lambda 函数内部的断点

【问题讨论】:

    标签: angular typescript rxjs extension-methods


    【解决方案1】:

    this 对象未被修改。尝试在连接管道的情况下返回this。而且因为你没有映射,你可以使用tap

    Observable.prototype.useCache = function<T>(this: Observable<T>, key: string) {
      const inCache = LocalStorage.get(key);
      if (inCache) {
        return of(inCache);
      }
      return this.pipe(
        tap((e: T) => LocalStorage.set(key, e))
      );
    };
    

    【讨论】:

    • 你能返回of(inCache)而不是长的new Observable&lt;T&gt;(observer =&gt; observer.next(inCache))吗?
    • 这是一个更好的选择。我盲目地复制和粘贴,然后调整了其他一些位,但错过了那个。干杯
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 2023-03-12
    • 1970-01-01
    • 2020-01-20
    • 2021-12-22
    • 1970-01-01
    相关资源
    最近更新 更多