Angular 中的高阶 Observable 多个任务

High-Order Observable multiple tasks in Angular

我想知道当反应式表单控件更改其值以避免嵌套订阅时执行不同 http 请求的正确方法。

我有两种方法,但我不确定这是最有效的方法。

选项 1:

this.form.get('someControl').valueChanges.pipe(debounceTime(500))
.subscribe(value => {

  /* Http Request 1 */
  http1$= this.http.post(route1, value).subscribe( res=>
  /*Tasks for Http Request1 */ 
 );

  /* Http Request 2 */
  http2$= this.http.post(route2, value).subscribe( res=>
  /*Tasks for Http Request2 */ 
 );
});

此选项不使用 switchMap,因此每次触发外部可观察对象时都会创建一个新订阅,但不会取消旧订阅。 :(

选项 2:

/* Http Request 1 */
this.form.get('someControl').valueChanges.pipe(debounceTime(500),
 switchMap(value=> this.http.post(route1, value)))
.subscribe(res=> {
  /*Tasks for Http Request1 */ 
 );
)};

/* Http Request 2 */
this.form.get('someControl').valueChanges.pipe(debounceTime(500),
 switchMap(value=> this.http.post(route2, value)))
.subscribe(res=> {
  /*Tasks for Http Request2 */ 
 );
)};

有没有办法让调用只订阅一次 valueChanges 事件?

提前致谢。

您可以使用 RxJS forkJoin 运算符来组合多个请求。尝试以下

this.form.get('someControl').valueChanges.pipe(
  debounceTime(500),
  switchMap(value => forkJoin(this.http.post(route1, value), this.http.post(route2, value)))
).subscribe(
  response => {
    // response[0] - response from 'this.http.post(route1, value)'
    // response[1] - response from 'this.http.post(route2, value)' 
  },
  error => {
    // handle error
  }
);