Angular 5 Subscribe read HttpStatusCode 204

拥有回忆 提交于 2019-12-13 20:28:39

问题


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

Example code:-

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

userSvc Function :-

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

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.

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

web-API code looks like this :-

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

回答1:


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.

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

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' } );
        }

And then consume it like this:

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) });


来源:https://stackoverflow.com/questions/54827379/angular-5-subscribe-read-httpstatuscode-204

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!