Ismail
Ismail

Reputation: 1316

JSON responce from REST as string in Angular

I have a REST service in Angular which returns JSON response. I need to get the response as string to do some pattern matching and value replacement.

I am using Angular 7. Below is my service.

getUIData(): Observable<any> {
    const url = `${this.baseUrl}/uiData`;
    return this.http.get<any>(url).pipe(
      catchError(this.handleError<any>('Get Data:'))
    );
  }

Upvotes: 0

Views: 601

Answers (2)

Ganesh
Ganesh

Reputation: 6016

By default HttpClient will return JSON Object

in your case you need to convert it to String. So do some changes like below,

getUIData(): Observable<any> {
    const url = `${this.baseUrl}/uiData`;
    return this.http.get<any>(url).map( response => JSON.stringify(response.data)).
      catchError(this.handleError<any>('Get Data:');
  }

as @dcg suggested use map instead of pipe to convert your response data to string in the Service method itself.

I hope it helps :).

Upvotes: 1

yanky_cranky
yanky_cranky

Reputation: 1363

You can do this in two ways :

1) set request headers as :

'Content-Type', 'text/plain; charset=utf-8'

2) Transform your response in stringified format inside map operator

JSON.stringify(data);

Note for second. it will still be JSON but stringified

Upvotes: 1

Related Questions