首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular5、响应和订阅

Angular5、响应和订阅
EN

Stack Overflow用户
提问于 2018-02-12 15:40:34
回答 1查看 47关注 0票数 1

我有两次对服务器的调用,它们彼此依赖,如下所示

代码语言:javascript
复制
    this.service.fetchPoints(this.dateStart, this.dateEnd).subscribe(
        response => {
            this.points = response;
            do something .....
        }
    );

    this.service.fetchSchedule(this.points.date).subscribe(
        response => {
            this.schedule = response;
        }
    );

this.service的代码如下:

代码语言:javascript
复制
fetchPoints(from:string, to:string) {
    return this.http.get(this.createUrl(`/api/congregations/fetch_points/${this.congregation.id}-${from}-${to}`));
}

第二个函数也返回observable建立依赖关系的最简单方法是这样编写它

代码语言:javascript
复制
      this.service.fetchPoints(this.dateStart, this.dateEnd).subscribe(
        response => {
            this.points = repsonse;
            this.service.fetchSchedule(this.points.date).subscribe(
                response => {
                    this.schedule = response;
                }
            );
        }
    );

但是这看起来很丑陋,有没有办法让它变得更好呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-12 16:08:26

你可以将你的Observable转换成一个Promise,但是你将会得到同样的东西。

代码语言:javascript
复制
import 'rxjs/add/operator/toPromise';

fetchPoints(from:string, to:string) {
    return this.http.get(this.createUrl(`/api/congregations/fetch_points/${this.congregation.id}-${from}-${to}`))
          .toPromise();
}

服务:

代码语言:javascript
复制
  this.service.fetchPoints(this.dateStart, this.dateEnd).then(
    response => {
        this.points = repsonse;
        this.service.fetchSchedule(this.points.date).then(
            response => {
                this.schedule = response;
            }
        );
    }
);

但是上面的代码并没有真正“整理”太多东西,所以我建议您将fetchSchedule移到它自己的方法中。

另外,在上面的代码中,我注意到您使用了两次限定了作用域的变量response,这非常令人困惑,所以如果您不采纳我的任何建议,我建议您将response更改为类似pointsResponsescheduleResponse的名称。

代码语言:javascript
复制
private getSchedule() {
    this.service.fetchSchedule(this.points.date).subscribe(
        response => {
            this.schedule = response;
        }
    );
}

然后,您的代码将如下所示:

代码语言:javascript
复制
  this.service.fetchPoints(this.dateStart, this.dateEnd).subscribe(
    response => {
        this.points = repsonse;
            getSchedule();
        );
    }
);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48741556

复制
相关文章

相似问题

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