Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get http response as a string in Angular 5

Given the source Angular Service code

@Injectable()
export class HomeContentService {

  constructor(private http: HttpClient) { }

  getContent(): Observable<string> {

    let fileURI = '/assets/content/home.md';
    let opt = { responseType: 'text' };
    return this.http.get<string>(
      fileURI,
      opt
    );

  }

Calling getContent() should return an Observable<string>. However, when I run ng serve, I get Type 'string' is not assignable to type 'json'.

After a few tries webpack seems to compile fine without me doing any changes, but the problem happens again anytime I close the process and try to ng serve again.

I guess there's something wrong with my setting responseType: 'text', but I don't know what it is. Googling wasn't helpful either.

Any ideas?

like image 946
gchiconi Avatar asked Jan 04 '23 03:01

gchiconi


1 Answers

You have to inline the options as this is the only way that the TypeScript transpiler can infer that you are wanting to return type Observable<string>.

getContent(): Observable<string> {
  let fileURI = '/assets/content/home.md';
  return this.http.get(fileURI, { responseType: 'text' });
}

See also Http ResponseType cannot be set #18586, refer to the comments made by alxhub.

like image 72
Igor Avatar answered Jan 16 '23 21:01

Igor