订阅时未触发 rxjs 管道 tap/map

rxjs pipe tap/map is not triggered when subscribe

我不知道为什么,但是当我将 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 函数内的断点

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))
  );
};