angular - rxjs pipe tap/map triggas inte när man prenumererar


Jag vet inte varför, men när jag använder Observable med förlängningsmetod och pipe, triggas inte pipe map eller tap.

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

Överallt annars kan jag sätta brytpunkter som stoppar där men inte inne i map-lambdafunktionen

Svar #1

Objektet this ändras inte. Försök att returnera this med pipen bifogad. Och eftersom du inte mappar, kan du bara använda en 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))
  );
};