我们创建
ob.pipe(map(),map(),map())
一直都有,
让myMaps = [map(),map(),map()]
然后致电
ob.pipe(myMaps)
以某种方式。
这是我的打字稿用例的简化版本
declare type InterceptorFunc = (m: Message) => Observable < Message >
export function interceptorMap(interceptorFunc: InterceptorFunc):
(source: Observable < Message > ) => Observable < Message > {
console.log("interceptorMap") //[1]never see this in the console
return (source: Observable < Message > ) => source.pipe(flatMap(e => {
console.log("interceptorMap: msg: ", e) //[2]nor this
return interceptorFunc(e);
}));
}
addInterceptor(interceptor: Function /*InterceptorFunc*/ ) {
this.interceptorFuncArray.push( < InterceptorFunc > interceptor)
}
/**
* Apply interceptors
*/
//message intercept
( < any > this.preReplayEventsSubject.asObservable()).pipe(
...(this.interceptorFuncArray.map(f => interceptorMap(f))),
map((m: Message) => {
console.log("Message after apply interceptors: ", m) //[3]see this in the console and the message appears like it has never flowed through any interceptor Funcs in the array
return m;
}))
.subscribe((m: Message) => {//[4]
this.replayEventsSubject.next(m);
});
因此,在注释[1]和[2]中,永远不会执行自定义运算符中的console.log语句。在注释[3]中,在运算符中更改的Message对象没有更改,但是执行console.log语句的事实表明该事件必须通过散布数组才能到达。
我尝试定义一个返回null的InterceptorFunc,然后将其放入过滤器中(e => !!)注释[3]和[4]代码仍然运行,其中具有null事件的过滤器应停止该消息的流完全对象。
谁能解释为什么会这样?
答案 0 :(得分:0)
我想最重要的部分是您可以give customized a function来pipe
操作员:
obs.pipe(
(observable) => doSomething(observable, ...),
otherOperators(callbackFunction)
)
这是一个简单的代码示例,可以为您提供答案:
// import rxjs
const {of} = rxjs;
const {map} = rxjs.operators;
/*
apply a chain of `map` operations
*/
function mapAll(obs, operations) {
return obs.pipe(
map(v => {
return operations.reduce((accVal, currentOp) => {
return currentOp(accVal)
}, v)
})
)
}
let result = [];
let observable = of(result);
// The idea here is to verify that each operation pushes into result
let op1 = (r) => {r.push(1); return r};
let op2 = (r) => {r.push(2); return r};
let op3 = (r) => {r.push(3); return r};
let operations = [op1, op2, op3];
observable.pipe(
(obs) => mapAll(obs, operations)
)
.subscribe(res => console.log(res));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.2.1/rxjs.umd.js"></script>
let
中的 RxJs < 5.5
运算符已替换为pipe
,它们具有相同的签名。我想您可以通过`let̀找到更多关于examples的信息,以了解如何编写自定义运算符。