【问题标题】:Waiting for POST to Complete and Returning the Status from Service等待 POST 完成并从服务返回状态
【发布时间】:2017-11-06 20:52:04
【问题描述】:

我正在使用来自'@angular/common/http' 的新HttpClient。我的组件和服务设置如下:

component.ts

public async saveComment() {
    this._service.postComment(this.comment);

    // I want to wait for the post to complete and then update my comments list below

    this.comments = await this._service.getComments();
}

service.ts

public postComment(comment: string) {
    this._http.post(this.serviceUrl, { comment })
        .subscribe(
        response => {
            console.log(response);
        });
}

post 不返回任何内容。它只在成功时返回200,如果不成功则返回错误状态。

如何等待我的组件在我的服务中调用 post 的 HTTP 响应状态?

【问题讨论】:

    标签: angular


    【解决方案1】:

    这不是人们通常做服务的方式。返回Observablefrom the service 并在组件中订阅:

    组件

    public saveComment() {
        this._service.postComment(this.comment)
            .subscribe(
                success => this.getComments(),  // See new method below, just ignore `success`.
                error => handleError(error)
            );
    }
    
    public getComments() {
        this._service.getComments()
            .subscribe(
                 comments => this.comments = comments,
                 error => this.handleError(error),
                 () => doSomethingElseOnceComplete(),
            );
    }
    

    服务

    public postComment(comment: string) {
        return this._http.post(this.serviceUrl, { comment });
    }
    
    public getComments(comment: string) {
        return this._http.get(this.serviceUrl);
    }
    

    请参阅我在 getComments() 上的补充:您可能想做同样的事情并将其包装在辅助函数中,而不是使其异步。这就是使用Observables 的意义所在:您将它们传递给周围并对其采取行动,非常像Promise

    会发生什么?

    next 回调(这里说明性地分配给success)将使用 REST 返回的值调用,这没什么,但我们不在乎,所以你可以忽略它,事实上它是null

    您可以使用next 回调仅在请求成功时调用这一事实来触发您的后续依赖操作,刷新 cmets。

    您可以在该错误处理程序中处理评论未能发布的错误。

    另请注意,从 Angular 4.3 开始,HttpClientModule 取代了旧的 HttpModule,最终将被弃用。

    【讨论】:

    • 感谢您的详细回答。这为我清除了一些东西。
    • @RyanBuening 很高兴听到这个消息!你很受欢迎。我有一段时间在 Observable 模型上加速发展,但我被说服了:一旦你掌握了它,它就会非常强大。
    猜你喜欢
    • 2016-09-10
    • 2011-09-08
    • 2016-04-13
    • 2020-01-02
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    相关资源
    最近更新 更多