Angular7: unable to set {responseType: 'text'}

Akber Iqbal picture Akber Iqbal · Dec 5, 2018 · Viewed 11k times · Source

Scenario: Upon an API call from Angular7, i am calling Node (via express) and returning chunked data of type string - I want to capture this string data and display it as string

Server-side: From Node backend, the data is being sent is 'text' and not json... the data is sent via multiple res.write('some strings') statements

client-side in Angular: I want an observable to process this data...

  1. when i don't mention any responseType [return this.http.get(this.streamURL );]... i get error:

SyntaxError: Unexpected token { in JSON at position 12 at JSON.parse ()

the error on stackBlitz and similar error at compile time on ng serve

  1. when i don't mention responseType as 'text [return this.http.get(this.streamURL , { responseType: 'text'});]... i get error at compile time:

ERROR in src/app/myS.service.ts(24,54): error TS2322: Type '"text"' is not assignable to type '"json"'

how can i capture 'text' data from my Node JS backend... i am using npm cors in my Node so no CORS errors there

Demo code available here: https://stackblitz.com/edit/angular-44sess

My Back-end is in the snippet below:

Answer

Ieremias Viorel picture Ieremias Viorel · Dec 5, 2018

I always use the following patterns in this case:

returnObservable(): Observable<any> {
  const requestOptions: Object = {
    /* other options here */
    responseType: 'text'
  }
  return this.http.get<any>(this.streamURL , requestOptions);
}

Hope it answers your question!