gpt4 book ai didi

angular - 如何用switchMap取消http请求?

转载 作者:可可西里 更新时间:2023-11-01 16:31:41 28 4
gpt4 key购买 nike

如果我向服务器发出新的 http 请求但它没有按我预期的方式工作,我想取消之前的 http 请求。

如果函数中的某些值发生变化,我想取消请求我的意思是如果值发生变化,旧请求应该取消,新请求应该创建为此我做了这件事

1)创建了一个主题 - 将被可观察者观看的事物
public stringVar = new Subject<string>();

2) 创建一个可观察对象来观察主题并发送更新流(您将订阅它以获取更新流)

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 Subject 中发出更新的值.由于 Observable 订阅只有一个并且已经存在,它将捕获发出的新值并在 switchMap 运算符的帮助下创建新的 http 请求。

FYI you have correctly chosen switchMap operator. It will discard latest network call if new event arrives in the meantime.

这是您的工作示例:

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);
}
}

关于angular - 如何用switchMap取消http请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56958362/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com