首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Angular:嵌套的HTTP调用-使代码更具可读性

Angular:嵌套的HTTP调用-使代码更具可读性
EN

Stack Overflow用户
提问于 2021-05-17 17:09:47
回答 1查看 57关注 0票数 0

假设我想通过调用REST API在Angular应用程序中获取数据,以便在Angular应用程序中显示数据。

我会把这样的东西叫做:

代码语言:javascript
运行
复制
this.http.get(this.configUrl).subscribe(response => {
  //do something
});

然而,我经常遇到这样的情况,我必须根据第一个REST API call.So获取更多数据,我的数据如下所示:

代码语言:javascript
运行
复制
  this.http.get(this.configUrl).subscribe(response => {
      //next call
      this.http.get(this.configUrl).subscribe(response => {
        //next call
        this.http.get(this.configUrl).subscribe(response => {
          //next call
          this.http.get(this.configUrl).subscribe(response => {
           //do something
           });
         });
      });
    });

我发现这很难读懂。有没有办法让它在Angular / Typescript中更具可读性,或者我做了一些根本错误的事情?

EN

Stack Overflow用户

发布于 2021-05-17 17:34:42

您可以使用管道运算符,如switchMap RxJS 来简化此嵌套调用;

代码语言:javascript
运行
复制
    this.http.get(this.configUrl)
      .pipe(map(
        res => res.json()),
        switchMap(data => {
          const data1 = data.sample_datum;
          return this.http.get(this.configUrl + "&data=" + data1);
        }),
        switchMap(data => {
          const data2 = data.sample_datum2;
          return this.http.get(this.configUrl + "&data=" + data2);
        }),
        switchMap(data => {
          const data3 = data.sample_datum3;
          return this.http.get(this.configUrl + "&data=" + data3);
        }),
        switchMap(data => {
          const data4 = data.sample_datum4;
          return this.http.get(this.configUrl + "&data=" + data4);
        }))
      .subscribe((d) => console.log("subscribe", d))

或者您可以使用await关键字来防止嵌套。

代码语言:javascript
运行
复制
    const data1 = await this.http.get(this.configUrl);
    const data2 = await this.http.get(this.configUrl + "&data=" + data1);
    const data3 = await this.http.get(this.configUrl + "&data=" + data2);
    const data4 = await this.http.get(this.configUrl + "&data=" + data3);
票数 2
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67566891

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档