Angular6 - Read response body of text/plain
Asked Answered
E

2

0

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);
}
Elastin answered 17/8, 2018 at 17:22 Comment(0)
C
6

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

Calamine answered 17/8, 2018 at 18:4 Comment(0)
S
1

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

}

Shortie answered 17/8, 2018 at 17:31 Comment(3)
I converted it to this line: return this.http.post(this.apiRoot + "User/add", registerUser, httpOptions).pipe(map((response: any) => response.text())); since the code you posted I think is not compatible with my version of rxjs (or I am failing with the imports). However, I receive the following error in the console: ERROR TypeError: response.text is not a functionElastin
Please add below to import map from rxjs: import 'rxjs/add/operator/map';Shortie
It still returns a compile error: Property 'map' does not exist on type 'Observable<Object>' which was the reason that I used the .pipeElastin

© 2022 - 2024 — McMap. All rights reserved.