【问题标题】:Angular Rxjs stops all previous request on click event and make new callAngular Rxjs 停止所有先前的点击事件请求并进行新调用
【发布时间】:2023-01-20 19:12:55
【问题描述】:

我是 Angular 的新手,遇到这样一种情况:在页面加载时,我必须在 ngOnit 上触发 4 个不同的 API,并在单击事件时在同一页面上有一个单击事件,我希望它会停止所有以前的调用,并使新的 API 调用。

代码。

ngOnInit(): void {
    this.getData('');
  }

getData(data) {
    const amount$ = this.service.getAmount(data).pipe(takeUntil(this.unSubscribe$));
    const rate$ = this.service.getRate(data).pipe(takeUntil(this.unSubscribe$));
    const applications$ = this.service.getApp(data).pipe(takeUntil(this.unSubscribe$));
    const statistics$ = this.service.getStat(data).pipe(takeUntil(this.unSubscribe$));
    applications$.subscribe(res => {
      if (res.success) {
        let d = res.dataSet;
        }
    }, (err) => {
    })
    ------ and another three subscribe here
  }

HTML

<button type="button" (click)="getData('abc')"
            >Event</button>

'abc' 是一个动态字符串,根据需要进行更改,然后单击按钮,我们将唯一字符串传递到 getData 函数中,并基于该字符串,我们在每次单击按钮时都会调用一个新的 API,但我希望每次点击它都会停止所有以前的 API 调用并点击新的 API。

【问题讨论】:

  • 你退订观察员吗?

标签: javascript angular promise rxjs


【解决方案1】:

这是switchMap 操作员的典型场景。

我会做的是这样的

// define a BehaviorSubject, i.e. a subject that emits a first vale as soon as 
// it is subscribed. In this case it emits an empty string, as in the ngOnInit
start$ = new BehaviorSubject<string>('')

// then define the Observable that runs the APIs with start$ as its starting point
execute$ = start$.pipe(
  // here you place switchMap which means: as soon as I get a value from 
  // upstream, I unsubscribe and preceding subscription and start a new subscription
  switchMap(val => {
     // with merge here I run all the 3 APIs concurrently
     return merge(amount$, rate$, applications$, statistics$)
  })
)

现在在 ngOnInit 中你创建了一个,也是唯一一个,订阅,就像这样

ngOnInit(): void {
    this.execute$.subscribe(// whatever is necessary)
}

在按钮点击事件的处理程序中,你nextstart$主题,即你让start$发出你想要的字符串

<button type="button" (click)="start$.next('abc')"
            >Event</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    相关资源
    最近更新 更多