[英]How to cancel http request with switchMap?
如果我向服務器發出新的 http 請求,我想取消之前的 http 請求,但它沒有按我的預期工作。
如果函數中的某些值發生更改,我想取消請求我的意思是如果值更改舊請求應該取消而新請求應該為此創建我已經這樣做了
1)創建一個主題 - 可觀察對象將觀看的事物public stringVar = new Subject<string>();
2)創建一個observable來觀察主題並發送更新流(您將訂閱此以獲取更新流)
public stringVar$ = this.stringVar.asObservable()
3)在特定函數中,我將值作為參數獲取,因此我執行這些步驟
testFunction(value){
this.stringVar.next(listValueSelected);
this.testOutput = this.stringVar$.pipe(
switchMap(() => {
return this.teseService.getEntries(val_one, val_two,val_three);
})
)
this.testOutput.subscribe(result => console.log(`${result}`));
}
當值將要更改但第一次只有一個請求是模式時,該請求是可取消的,但是當我第二次單擊它時,它會調用 api 兩次,這將繼續。我的代碼有什么問題?
在 component.ts
export class TestComponent {
testOutput :Observable<any>;
stringVar = new Subject<number>();
stringVar$ = this.stringVar.asObservable();
testResult(selectedValue) {
this.stringVar.next(selectedValue);
this.stringVar$.subscribe(data => {
});
this.testOutput = this.stringVar$.pipe(
switchMap(() => {
return this.testService.getTestEntries(this.x,this.y,this.z);
})
)
this.testOutput.subscribe(result => console.log(`${result}`));
}
}
在服務文件中
getTestEntries(x, y,selectedValue): Observable<any>{
let apiUrl = selectedValue=='3'?this.baseUrl1:this.baseUrl ;
return this.http.post(apiUrl,obj).map((response: Response) => {
return response;
})
}
如果組件中的值“selectedValue”發生變化,我想取消我的舊請求並創建新請求。
我相信每當您單擊按鈕時都會調用您的方法testResult(selectedValue)
,因此這將創建新的 Observable 並在您單擊按鈕並調用該方法時訂閱它。 這些新的 Observable 訂閱導致了多個網絡請求。
理想情況下,您只想在構造函數中訂閱stringVar$
一次,並且當發生變化時只在stringVar
主題中發出更新的值。 由於 Observable 訂閱只有一個並且已經存在,它將捕獲發出的新值並在switchMap
運算符的幫助下創建新的 http 請求。
僅供參考,您已正確選擇
switchMap
運算符。 如果同時有新事件到達,它將丟棄最新的網絡調用。
這是您的工作示例:
export class TestComponent {
testOutput: Observable<any>;
stringVar = new Subject<number>();
stringVar$ = this.stringVar.asObservable();
constructor() {
this.testOutput = this.stringVar$.pipe(
switchMap(() => {
return this.testService.getTestEntries(this.x, this.y, this.z);
}),
);
this.testOutput.subscribe((result) => console.log(`${result}`));
}
testResult(selectedValue) {
this.stringVar.next(selectedValue);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.