Angular 5 订阅读取 HttpStatusCode 204 [英] Angular 5 Subscribe read HttpStatusCode 204

查看:22
本文介绍了Angular 5 订阅读取 HttpStatusCode 204的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用 Angular 5 并调用 API 来获取数据.

I am using Angular 5 in the project and making API calls to fetch the data.

示例代码:-

this.userSvc.addPhone(this.userID, this.countryCode, this.phoneNumber)
   .subscribe(data => {
       console.log('Phone Added Successfully')
    },
    (err: HttpErrorResponse) => { console.log(err.message) });

userSvc 函数 :-

    addPhone(userId, countryCode, phoneNumber) {
    return this.HttpClient.Post(this.rootUrl + "add-phonetouser?id=" + userId + "&countrycode=" + countryCode + "&phonenumber=" + phoneNumber
        , { headers: this.header });
}

从 web-api 方法,我试图传递 NoContent HttpCode 并想读取角度端的状态代码.

From the web-api method, i am trying to pass the NoContent HttpCode and would like to read the status code on the angular side.

现在我想了解如何从角度读取此 NoContent HttpStatusCode.

Now i would like to understand how do i read this NoContent HttpStatusCode from the angular side.

web-API 代码如下所示:-

web-API code looks like this :-

var user = await UserManager.FindByName(username);
if (user == null) {
   return Request.CreateResponse(HttpStatusCode.NoContent, "User not found.");
} else {}

推荐答案

来自 Angular Docs:

from Angular Docs:

响应正文不会返回您可能需要的所有数据.有时服务器返回特殊标头或状态代码以指示某些对应用程序工作流很重要的条件.

The response body doesn't return all the data you may need. Sometimes servers return special headers or status codes to indicate certain conditions that are important to the application workflow.

告诉 HttpClient 你想要完整的响应选项:

Tell HttpClient that you want the full response with the observe option:

您需要在来自 Angular 的 API 调用中使用 { observe: 'response' }.

You need to use { observe: 'response' } in your API call from Angular.

 addPhone(userId, countryCode, phoneNumber): Observable<HttpResponse<any>> {
        return this.HttpClient.Post(this.rootUrl + "add-phonetouser?id=" + userId +
         "&countrycode=" + countryCode + "&phonenumber=" + phoneNumber
            , {}, { headers: this.header,  observe: 'response' } );
        }

然后像这样消费它:

this.userSvc.addPhone(this.userID, this.countryCode, this.phoneNumber)
   .subscribe(data => {
       console.log(data.status);
       console.log(data.body);
    },
    (err: HttpErrorResponse) => { console.log(err.message) });

这篇关于Angular 5 订阅读取 HttpStatusCode 204的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆