使用 TypeScript 将 RxJS 操作符组合成新的操作符 [英] Combine RxJS operators into new operator using TypeScript
本文介绍了使用 TypeScript 将 RxJS 操作符组合成新的操作符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我经常发现自己将相同的运算符序列添加到可观察对象中,例如
I frequently find my self adding the same sequence of operators to observables, e.g.
observable$
.do(x => console.log('some text', x))
.publishReplay()
.refCount();
我正在寻找一种方法将这 3 个运算符组合到一个小的可重用运算符(例如 .cache('some text')
)中,我可以将其链接到任何可观察对象.我如何在 Typescript 中定义它,以便我可以像使用 rxjs 运算符一样导入 rxjs/Observable 和这个运算符?
I'm looking for a way to combine these 3 operators in a small reusable operator (e.g. .cache('some text')
) that I can chain to any observable. How can I define this in Typescript, so that I could import rxjs/Observable and this operator, like I do with rxjs operators?
推荐答案
要实现您所描述的运算符,请创建一个具有以下内容的 cache.ts
文件:
To implement the operator you have described, create a cache.ts
file with the following content:
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/do";
import "rxjs/add/operator/publishReplay";
// Compose the operator:
function cache<T>(this: Observable<T>, text: string): Observable<T> {
return this
.do(x => console.log(text, x))
.publishReplay()
.refCount();
}
// Add the operator to the Observable prototype:
Observable.prototype.cache = cache;
// Extend the TypeScript interface for Observable to include the operator:
declare module "rxjs/Observable" {
interface Observable<T> {
cache: typeof cache;
}
}
然后像这样消费它:
import { Observable } from "rxjs/Observable";
import "rxjs/add/observable/of";
import "./cache";
let cached = Observable.of(1).cache("some text");
cached.subscribe(x => console.log(x));
这篇关于使用 TypeScript 将 RxJS 操作符组合成新的操作符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文