我有一个用例,每当一个新的请求被触发时,任何已经在飞行中的http请求都应该被取消/忽略。
(如):
我认为,switchMap取消了可观测值/保持了发出可观测值的顺序。
摘录自我的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' });
}上面的实现不起作用。有人能找出这个用法的正确实现吗?
发布于 2018-03-12 18:50:52
下面是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
}
}发布于 2018-02-28 18:35:39
看起来你在创造多个可观察的东西。从您的示例中可以看出这一点,但似乎每次提出请求时都会调用Observable.of。这每次都会创建一个新的可观测流,因此对于后续的每个调用,您都会得到一个新的流,而前一个流不会被取消。这就是为什么.switchMap不能工作的原因。
如果希望.switchMap取消HTTP请求,则需要它们使用相同的可观察流。您想要使用的源取决于触发http请求的确切内容,但您可以使用类似于Subject的方法来管理它。
const makeRequest$ = new Subject();
const myResponse$ = makeRequest$.pipe(switchMap(() => this.service.getStuff()));您可以订阅myResponse$以获得响应。当您想要触发请求时,您可以执行makeRequest$.next()。
https://stackoverflow.com/questions/49036074
复制相似问题