【问题标题】:Angular how to handle sequential requests and how handle loading var?Angular如何处理顺序请求以及如何处理加载var?
【发布时间】:2021-03-15 17:00:50
【问题描述】:

我保存了个人资料,一旦请求成功,我会再次请求创建付款。现在的代码是这样的

 this.profileService.saveProfile(dataProfile).pipe(
      catchError(e => of(null))
    ).subscribe(res => {
      if (res) { // if user saved profile data
       const data = {
   params: {
            user: {
              surname: this.formInfo.get('surname').value,
              name: this.formInfo.get('name').value,
              father_name: this.formInfo.get('father_name').value,
              iin: this.formInfo.get('iin').value,
            },
            tariff: obj ? {
              months: obj.Months,
              amount: obj.Amount,
              amountByMonth: obj.AmountByMonth
            } : null,
}
        this.buyService.create(data).pipe( ... 
  }

让这段代码变得更好的最好方法是什么?我在RXjs 中阅读了有关concatMap 运算符的信息,但这与Observables 数组有关,如果用户保存自己的数据,这里我只有一个响应。 另外,我应该如何在此处为每个请求单独处理 loading 变量?

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    concatMap 是大多数时候用来连接 2 个或多个 http 操作的运算符。

    因此,在这种情况下,您的代码可能如下所示

    this.profileService.saveProfile(dataProfile).pipe(
      concatMap(resp => {
         const data = {
            params: {
              // your params
            }
         }
         // the function passed to concatMap MUST return an Observable
         return this.buyService.create(data)
      })
    ).subscribe(
       next: result => {// manage the result},
       error: err => {// manage the error}
    )
    

    老实说,当您编写“在 RXjs 中的 concatMap 运算符,但这与 Observables 数组有关”时,我不明白。

    您可能会从this article 获得一些有关典型 http 相关用例的灵感。

    【讨论】:

    • 好吧,我的意思是我只使用来自saveProfile 的布尔响应,如果用户保存了自己的数据,那么我会发出另一个请求。我在想,当我使用 concatMap 时,我将第一个 http req 的数据传递给下一个 http 请求。
    • 你可以忽略第一次服务调用传入的数据,比如concatMap(() => {// do stuff; return this.buyService.create(data)})。在这种情况下,只有在前一个请求成功时才输入concatMap,否则您将进入指定为subscribe 输入的error 函数。
    猜你喜欢
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2011-04-05
    • 2012-01-30
    • 2011-02-17
    相关资源
    最近更新 更多