带有角度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.
例如 :
For eg:
- 一个请求(例如#2)进入,而请求#1花费的时间太长,无法响应/网络连接速度变慢.
- 在这种情况下,即使#1响应返回HTTP响应,#2也会从服务器获得非常快速的响应,然后在任何时候 可观察到的应该被忽略.
- 我面临的问题是,首先组件显示请求2的响应值,并在请求1完成后再次更新(这不应该发生).
- A request (say #2) comes in while the request #1 takes too long to respond / slow network connectivity.
- In this case #2 gets a very quick response from server then at any point even if the #1 comes back with a response the HTTP response observable should be ignored.
- The problem i face is, first the component displays response values from request #2 and gets updated again when req #1 completes (this should not happen).
我发现switchMap取消了可观察对象/保持了可观察值的发出顺序.
I figured that switchMap cancels obervables / maintains the order in which the observable values are emitted.
从我的服务中摘录.
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屋!
查看全文