Angular5,响应和订阅

时间:2018-02-12 07:40:34

标签: javascript angular

我有两次对服务器的调用,这样就相互依赖

self.view.layoutIfNeeded()

this.service是这样的代码:

    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;
        }
    );

第二个函数也返回fetchPoints(from:string, to:string) { return this.http.get(this.createUrl(`/api/congregations/fetch_points/${this.congregation.id}-${from}-${to}`)); } 最简单的依赖方法就是像这样写

observable

但这看起来很难看,有没有办法让它变得更好?

1 个答案:

答案 0 :(得分:0)

您可以将Observable转换为Promise,但实际上你会做同样的事情。

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();
}

服务:

  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

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

您的代码将如下所示:

  this.service.fetchPoints(this.dateStart, this.dateEnd).subscribe(
    response => {
        this.points = repsonse;
            getSchedule();
        );
    }
);