Angular6 - Read response body of text/plain

浪子不回头ぞ 提交于 2019-12-11 15:19:18

问题


I am performing a sign-up action and in my backend when the user successfully registers I return his id e.g. "105" and when the register fails (user already exists) I return "USER_EXISTS". I have checked the request on Postman and the body of the response is correct.
In both cases, I return "plain/text".

However, I am not able to find how to get the body of the response through the Observable object that I get return.

In register.component.ts:

userExists = "";
onSubmit() {

    const newUser : RegisterUser = {  email: this.register.email,
                                  password: this.register.password,
                                  firstName: this.register.firstName,
                                  lastName: this.register.lastName,
                                  phoneNumber: this.register.phoneNumber}


    this.registerService.addUser(newUser)
    .subscribe(response => (this.userExists = response)); //The purpose of this line is to get the body of the text/plain response and assign it into the this.userExists string
}

In RegisterService.service.ts

addUser (registerUser) {

    return this.http.post(this.apiRoot + "User/add", registerUser, httpOptions);
}

回答1:


By default angular 6 produce JSON reponse if you want text/plain you should set responseType as 'text'

 addUser (registerUser) {
    return this.http.post(this.apiRoot + "User/add", {responseType: 'text'});
 }

try to append it in httpOptions

check it text/plain




回答2:


In RegisterService.service.ts, add map and convert response to text as below:

addUser (registerUser) {

return this.http.post(this.apiRoot + "User/add", registerUser, httpOptions).map(res => res.text());

}



来源:https://stackoverflow.com/questions/51900264/angular6-read-response-body-of-text-plain

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