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

自作多情 提交于 2020-01-04 03:33:12

问题


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

  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:

app.get('/obs/responseWrite', cors(), function(req, res){
  var j=0;
  
  const headers = { 
    'Content-Type': 'text',     
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
    'Access-Control-Max-Age': 2592000, // 30 days
  };
  res.writeHead(200,headers);
  
  for(var i=0; i<50000; i++){
    /* setInterval(function() {    res.write("returning j:["+ j + "]. "); j=j+1; if(j>=100){res.end();} }, 1000); */
    var myObj =  { return : i };
    var myStr= JSON.stringify(myObj);
    console.log(myStr);
    res.write(myStr);
  }
  setInterval(function() {    res.end(); }, 15000);
  
});

回答1:


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!




回答2:


You can't use return generic type. In documentation generic type is only for 'json'. This mean you need use get like this:

return this.http.get(this.streamURL, { responseType: "text"});

See in documentation https://angular.io/api/common/http/HttpClient#get You are interest Overload #11 and now you are using Overload #13

Finally this is link for your code with update: https://stackblitz.com/edit/angular-gv1tkl?file=src/app/myS.service.ts

EDIT 1

I pasted wrong link to stackblitz. Correct above.



来源:https://stackoverflow.com/questions/53627244/angular7-unable-to-set-responsetype-text

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