避免嵌套订阅电话

时间:2019-07-16 23:28:01

标签: angular rxjs

我有一个按钮,单击它会拨打服务电话。最后,我想通过电子邮件通知用户。该电子邮件将通过另一个服务电话发出。

public submitForm = (data, selected = {} ) => {
    console.log(data);
    this.service['submit'].post({body: data}).subscribe(
    () => { null },
    error => {
       console.log(error);
    };
    () => {
         // second subscribe
        this.service['email']['post']({ body: theForm.value }).subscribe(
        () = > {
           // data processing
         }
       );
     }
     );}

您看到它是嵌套的订阅。我使用angular 5和rxjs 5.5。如何避免呢?

更新:

通过评论,我添加了服务代码

public readonly service: SwaggerService

例如,实际上所有服务都在asp.net Web API中

[HttpPost]
[Route("email")]
public ActionResult postEmail([FromBody]EmailBody email)
{}

2 个答案:

答案 0 :(得分:0)

您可以使用switchMap避免这样的嵌套订阅:

public submitForm = (data, selected = {} ) => {
  console.log(data);
  this.service['submit'].post({body: data})
      .switchMap(() => {
        return this.service['email']['post']({ body: theForm.value })
                  .catch(err => {
                    //handle your error here

                    //HERE YOU NEED TO DO YOUR SELF; MAKE SURE TO RETURN AN OBSERVABLE FOR HERE.
                    //I ON RXJS 6.4; So I am not sure what is `of` operator in rxjs 5.5
                    //I guss it is Observable.of
                    return Observable.of(err);
                  });
      })
      .catch(err => {
        //handle your error here

        //HERE YOU NEED TO DO YOUR SELF; MAKE SURE TO RETURN AN OBSERVABLE FOR HERE.
        //I ON RXJS 6.4; So I am not sure what is `of` operator in rxjs 5.5
        //I guss it is Observable.of
        return Observable.of(err);
      })
      .subscribe((resultOfSecondCall) => {
        //do your processing here...
        console.log(resultOfSecondCall);
      });

   }

答案 1 :(得分:0)

那不是我要做的方式。您尚未发布任何service代码,因此很难准确地告诉您如何实现。我将假设您的服务代码除了对服务器进行http调用(因此返回承诺/等待的内容)之外什么都不做

await this.service['submit'].post({body: data});
await this.service['email']['post']({ body: theForm.value });

在标准rxjs / HttpClient上使用Promises似乎没有任何好处。唯一真正的要求似乎是您需要先执行一次调用(成功),然后才能释放电子邮件。我只会使用await编写两行代码,而不是在此处链接一些可观察对象。

作为旁注,为了await进行HttpClient调用,您必须先将其转换为promise。 IE:this.httpClient.post(url, data).toPromise();

相关问题