我想有两个管道附加到HttpClient的请求,将执行一些功能的请求,当请求完成时。到目前为止,我已经找到了"finalize“运算符,用于在请求完成时执行函数,但我找不到用于请求启动的等效运算符。
到目前为止我的代码如下:
this.http.get<MyModel>('api/model')
.pipe(
// TODO missing something for startup
finalize(() => console.log('on start'))
)
.subscribe(result => {
console.log(result);
});如何实现这一结果?RxJS中有没有内置的运算符,还是我应该自己写?或者可能有其他选择?
发布于 2018-08-23 19:47:58
编辑:我找到了一个更好,更少人知道的解决方案。有一个defer观察值创建函数,而不是一个运算符。
它可以像这样使用:
defer(() => {
console.log('on start');
return this.http.get<MyModel>('api/model').pipe(
finalize(() => console.log('on finish'))
)
}).subscribe(result => {
console.log(result);
});最棒的是,它捕获了闭包中的HttpClient,您可以在不订阅的情况下传递此可观察对象。
startWith是你能得到的最接近的运算符。它需要匹配http结果的类型。
发布于 2018-08-23 22:48:50
基于带有startWith运算符的@Tomasz Błachut建议。它需要一些技巧,但它的工作与预期的一样。
其思想是将startWith运算符与立即调用的函数一起使用,该函数将执行我想要的操作并返回null。然后我们在订阅中添加skip(1)来避免这个null。
它的工作方式与预期一致。最终代码:
this.http.get<MyModel>('api/model')
.pipe(
startWith((() => {
console.log('on start');
return null;
})()),
skip(1),
finalize(() => console.log('on end'))
)
.subscribe(result => {
console.log(result);
});https://stackoverflow.com/questions/51985069
复制相似问题