【问题标题】:Using an Angular 2 http.post without subscribing? Or am I thinking of it wrong?在不订阅的情况下使用 Angular 2 http.post?还是我想错了?
【发布时间】:2016-12-04 10:37:20
【问题描述】:

有没有办法只告诉服务器更新数据而不订阅?跳过返回语句和订阅似乎会使 http 调用无效。

就我而言,我的数据库人员创建了一堆不返回任何内容的存储过程,有时我想在我的服务中执行类似这样的简单操作:

public setItem(item: IRequestItem) {
        this.http.post('api/items', item);
    }

并在我的组件中这样调用它:

save() {
        var comp = this;
        this.items.forEach(function(item) {
            comp.service.setItem(item)
        });
    }

相反,我必须在服务中做这样的事情:

public setItem(item: IRequestItem) {
        return this.http.post('api/items', item);
    }

然后在组件中这样调用:

save() {
        var comp = this;
        this.items.forEach(function(item) {
            comp.service.setItem(item).subscribe(r => console.log(r));
        });
    }

这会返回很多这些:

Response {_body: "", status: 204, ok: true, statusText: "No Content", headers: Headers…}
_body : ""
headers : Headers
ok : true
status : 204
statusText : "No Content"
type : 2
url : "http://localhost:56018/api/items"
__proto__ : Object

我只是在学习,所以也许我看错了。我可以解释该响应对象中的某些内容,让我知道操作是失败还是成功?或者是否有另一种语法只会返回成功或失败,而不是令人困惑的“无内容”响应?

【问题讨论】:

标签: angular http-post observable angular2-services


【解决方案1】:

为了触发请求,你需要调用subscribe,但你不需要从服务返回可观察的请求并从组件调用它,你可以在服务内部调用订阅。

setItem(item: RequestItem) {
  this.http.post('api/items', item)
    .subscribe({ error: e => console.error(e) });
}

现在在上述情况下,服务将立即返回,请求完成之前,但将发出请求并从服务内记录任何错误。

【讨论】:

    猜你喜欢
    • 2016-10-27
    • 2020-04-19
    • 2017-12-25
    • 1970-01-01
    • 2021-12-21
    • 2019-03-18
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多