处理嵌套订阅的更好方法

时间:2018-10-09 10:45:18

标签: angular subscription

我有以下代码

this.subscriptions.push(this.loginservice.userdetails$.valueChanges().subscribe(data => {  // subscribing for user data... if any of the logged in user details changed
  this.lgUser = data;
  this.toFilter.subscribe(filter => {   // subject filter value of a dropdown
    this.subscriptions.push(this.service.getlist(this.lgUser.oid, filter).subscribe(res => { // subscribing to get list data
     // do some operation on res
    }));
    this.subscriptions.push(this.service.countValue(this.lgUser.oid, filter).subscribe(res => { // subscribing to get count value
      this.lCount = res.length;
    }));

  })
}));

如何使其变得更加突出

谢谢

1 个答案:

答案 0 :(得分:1)

好吧,我认为这很干净:

this.loginservice.userdetails$
  .valueChanges()
  .pipe(
    tap(data => this.lgUser = data),
    switchMap(data => this.toFilter.pipe(
      tap(filter => this.service.countValue(this.lgUser.oid, filter)
        .pipe(take(1))
        .subscribe(res => this.lCount = res.length)
    )),
    switchMap(filter => this.service.getlist(this.lgUser.oid, filter))
  ).subscribe(res => {
    // Do something on res
  });
  • 从聆听输入内容的变化开始。
  • 每次更改时,您将使用输入内容更新this.lgUser
  • 然后您切换到toFilter并使用switchMap取消先前的待处理请求
  • 您只需致电countValue即可获取数据并将其存储在lCount
  • 然后,您切换到service.getList并取消以前的待处理请求
  • 您仅需一个选项,即可在其中找到所需的内容。