小编Hit*_*tsa的帖子

如何使用switchMap取消http请求?

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

如果函数中的某些值发生更改,我想取消请求我的意思是如果值更改旧请求应该取消并且新请求应该为此创建我已经这样做了

1) 创建了一个主题 - 将被监视的东西observable
public stringVar = new Subject<string>();

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

public stringVar$ = this.stringVar.asObservable()
Run Code Online (Sandbox Code Playgroud)

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}`));
    } 
Run Code Online (Sandbox Code Playgroud)

当值将要更改但第一次只有一个请求是模式时,该请求是可取消的,但是当我第二次单击它时,它会调用 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}`));
    }

}
Run Code Online (Sandbox Code Playgroud)

在服务文件中

getTestEntries(x, …
Run Code Online (Sandbox Code Playgroud)

http observable rxjs angular switchmap

6
推荐指数
1
解决办法
5703
查看次数

标签 统计

angular ×1

http ×1

observable ×1

rxjs ×1

switchmap ×1