简体   繁体   English

Angular5,响应并订阅

[英]Angular5, response and subscribe

i have 2 calls to server that depends on each other like this 我有两个这样相互依赖的服务器呼叫

    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 is code like this: this.service是这样的代码:

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

second function also returns observable the easiest way to make dependency is to write it like this 第二个函数也返回observable的最简单的使依赖的方法是这样写

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

but this looks ugly, is there a way to make it better? 但这看起来很难看,有没有办法使它更好?

You could convert your Observable to a Promise , but you will be acheving the same thing really. 您可以将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();
}

Service: 服务:

  this.service.fetchPoints(this.dateStart, this.dateEnd).then(
    response => {
        this.points = repsonse;
        this.service.fetchSchedule(this.points.date).then(
            response => {
                this.schedule = response;
            }
        );
    }
);

But the above does not really "tidy" much up, so what I would suggest is that you move the fetchSchedule into it's own method. 但是上面的内容并没有真正“整理”很多,所以我建议您将fetchSchedule移入它自己的方法中。

Also in the above code I noticed you are using the scoped variable response twice, that is quite confusing, so if you don't take any of my suggestions, I suggest that you change response into something like pointsResponse and scheduleResponse . 同样在上面的代码中,我注意到您两次使用了范围变量response ,这很令人困惑,因此,如果您不采纳我的任何建议,建议您将response更改为pointsResponsescheduleResponse

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

Your code would then look like: 您的代码将如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM