问题
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