mpe*_*rle 5 observable rxjs angular switchmap angular-httpclient
每当触发新请求时,我都有一个用例,任何已经在进行中的 http 请求都应该被取消/忽略。
例如:
- 一个请求(比如#2)进来,而请求#1 响应时间太长/网络连接慢。
- 在这种情况下,#2 从服务器获得非常快的响应,然后在任何时候,即使 #1 返回响应,HTTP 响应 observable 也应该被忽略。
- 我面临的问题是,首先组件显示来自请求 #2 的响应值,并在请求 #1 完成时再次更新(这不应该发生)。
我认为 switchMap 取消了 obervables / 维护了发出 observable 值的顺序。
摘自我的 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' });
}
Run Code Online (Sandbox Code Playgroud)
上面的实现不起作用。有人能找出这个用例的正确实现吗?
Exp*_*lls 11
看起来您正在创建多个可观察对象。从您的示例中不清楚,但似乎您Observable.of每次想提出请求时都打电话。这每次都会创建一个新的Observable 流,因此对于每个后续调用,您都会获得一个新流,并且不会取消前一个流。这就是.switchMap不工作的原因。
如果要.switchMap取消 HTTP 请求,则需要它们使用相同的可观察流。您要使用的源 Observable 取决于触发 http 请求的确切原因,但您可以使用类似Subject.
const makeRequest$ = new Subject();
const myResponse$ = makeRequest$.pipe(switchMap(() => this.service.getStuff()));
Run Code Online (Sandbox Code Playgroud)
您可以订阅以myResponse$获取回复。任何时候你想触发一个请求,你都可以做makeRequest$.next()。
我有以下代码摘录,其中 switchMap 实现成功。
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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11966 次 |
| 最近记录: |