带有角度 HttpClient 的 RxJs switchMap [英] RxJs switchMap with angular HttpClient
本文介绍了带有角度 HttpClient 的 RxJs switchMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
每当触发新请求时,我都有一个用例,任何已经在进行中的 http 请求都应该被取消/忽略.
I have a use case whenever a new request is triggered, any http requests that are already in flight should be cancelled / ignored.
例如:
- 一个请求(比如 #2)传入,而请求 #1 响应时间太长/网络连接速度慢.
- 在这种情况下,#2 从服务器获得非常快的响应,然后在任何时候,即使 #1 带着响应返回 HTTP 响应observable 应该被忽略.
- 我面临的问题是,首先组件显示来自请求 #2 的响应值,并在请求 #1 完成时再次更新(这不应该发生).
我认为 switchMap 取消了 obervables/维护了发出 observable 值的顺序.
I figured that switchMap cancels obervables / maintains the order in which the observable values are emitted.
摘自我的 service.ts
Obervable.of('myServiceUrl')
.switchMap(url => this.httpRequest(url) )
.subscribe( response => {
// implementation
/** Update an observable with the
with latest changes from response. this will be
displayed in a component as async */
});
private httpRequest(url) {
return this.httpClient.get('myUrl', { observe: 'response' });
}
上述实现不起作用.有人能找出这个用例的正确实现吗?
The above implementation doesn't work. Could some one figure out the correct implementation for this usecase.
推荐答案
我有以下代码摘录,switchMap 实现成功.
I have the below code excerpt with which the switchMap implementation was successfull.
class MyClass {
private domain: string;
private myServiceUri: subject;
myData$: Observable<any>;
constructor(private http: HttpClient) {
.....
this.myServiceUri = new Subject();
this.myServiceUri.switchMap(uri => {
return this.http.get(uri , { observe: 'response' })
// we have to catch the error else the observable sequence will complete
.catch(error => {
// handle error scenario
return Obervable.empty(); //need this to continue the stream
});
})
.subscribe(response => {
this.myData$.next(response);
});
}
getData(uri: string) {
this.myServiceUri.next(this.domain + uri); // this will trigger the request
}
}
这篇关于带有角度 HttpClient 的 RxJs switchMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文