javascript - Angular5,回复并订阅

标签 javascript angular

我有 2 个对服务器的调用,它们像这样相互依赖

    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 的代码如下:

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

第二个函数也返回observable最简单的依赖方法就是这样写

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

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

最佳答案

您可以将您的 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();
        );
    }
);

关于javascript - Angular5,回复并订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48741556/

相关文章:

javascript - Angular 2 服务变量在模板中引用时给出控制台错误

javascript - 我如何在 document.write 中动态更改 iframe 的大小

javascript - 当 http get 请求状态返回 404 时显示 Angular Material mat-error

javascript - 使用 javascript 创建一个唯一的对象标识符

javascript - Webpack 没有将 css 复制到 dist

angular - Material 垫-选择名称属性

angular - 失败 : Can't resolve all parameters for MatDialogRef: (?,?,?)。单元测试 Angular 项目

javascript - 搜索另一个对象数组中的值列表,并使用单个 for 循环更改对象数组中的一个键

javascript - window.open() 在 JS 函数中无法正常工作

javascript - JQuery SlideToggle() 执行缓动的每一步函数