【问题标题】:High-Order Observable multiple tasks in AngularAngular 中的高阶 Observable 多个任务
【发布时间】:2020-06-26 11:42:14
【问题描述】:

我想知道当响应式表单控件更改其值以避免嵌套订阅时执行不同 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,因此每次外部 observable 触发时都会创建一个新订阅,但不会取消旧订阅。 :(

选项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 事件?

提前谢谢你。

【问题讨论】:

    标签: angular rxjs httprequest


    【解决方案1】:

    您可以使用 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
      }
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-19
      • 1970-01-01
      • 2011-03-24
      • 2019-06-09
      • 1970-01-01
      • 1970-01-01
      • 2018-01-17
      相关资源
      最近更新 更多