【问题标题】:Angular & rxjs - trying to prevent nested .subscribes using mergeMap produces a TS2684 errorAngular & rxjs - 尝试使用 mergeMap 防止嵌套的 .subscribe 会产生 TS2684 错误
【发布时间】:2018-03-09 22:54:40
【问题描述】:

我有两个连续的 http 请求,其中我将一些数据发送到我的后端以创建一个客户(将其视为一个组),然后从第一个请求的返回数据中创建一个属于该客户的新用户/ 团体。我正在使用带有表单的模式窗口来收集数据,在顺序请求完成后提交时我关闭了模式窗口..

这是我保存收集的数据并创建客户和用户的方法,注意两个嵌套的.subscribes...不是最好的实现,我想防止“厄运金字塔”。这是我的原...

public onSave(): void {}
  const customerData = this.dialogForm.getRawValue();
  const newUser: any = {
    Email: customerData.Email,
    IsActive: true,
    ResetPassword: false,
    Roles:[]
  };

  // add a new customer
  this.customersService.addCustomer(customerData).subscribe((res: any) => {
    newUser.ClientID = res.ID;
    // create the user
    this.usersService.create(newUser).subscribe(() => this.dialogRef.close(false));
  });
}

现在我想重构嵌套的 .subscribes。我想我需要使用.pipemergeMapdo...我写了这个...

// add a new customer
this.customersService.addCustomer(customerData).pipe(
      mergeMap(res => {
        newUser.ClientID = res.ID;
        return <Observable<any>> this.usersService.create(newUser)
      }
    ).do(() => this.dialogRef.close(false)));

这显然行不通。我的 IDE 也收到以下 TS 错误

错误:(108, 7) TS2684: 'void' 类型的 'this' 上下文不是 可分配给“Observable”类型的方法“this”。

有人可以帮我解决这个问题吗?如果我需要改写我的问题,或者缺少某些内容,请告诉我。

【问题讨论】:

  • 108 是哪一行?
  • 老实说,我真的没有看到你的尝试有什么问题会导致该错误(在已经写完答案之后再说这个:-))

标签: angular rxjs


【解决方案1】:

你可以使用

this.customersService.addCustomer(customerData)
  .map(customer => {
    return {...newUser, ClientID: customer.ID};
  })
  .switchMap(user => this.usersService.create(user))
  .subscribe(() => this.dialogRef.close(false));

或者,如果您更喜欢可管道操作符:

this.customersService.addCustomer(customerData).pipe(
  map(customer => {
    return {...newUser, ClientID: customer.ID};
  }),
  switchMap(user => this.usersService.create(user))
).subscribe(() => this.dialogRef.close(false));

【讨论】:

  • 2个sn-ps有什么区别?
  • 区别正是我所说的:一个使用管道运算符,另一个不使用。
  • 即使使用此更改的代码,我仍然会收到错误“错误:(113, 7) TS2684: 'void' 类型的 'this' 上下文不可分配给 'Observable' 类型的方法的 'this' '。”
  • 那您能把客服和用户服务贴一下吗?我认为打字是错误的。
猜你喜欢
  • 2020-10-06
  • 2018-03-30
  • 1970-01-01
  • 2019-01-31
  • 2018-07-31
  • 2019-09-19
  • 2021-11-02
  • 1970-01-01
  • 2021-01-03
相关资源
最近更新 更多