Requesting non-JSON data

​Not all APIs return JSON data. In this next example, a DownloaderService method reads a text file from the server and logs the file contents, before returning those contents to the caller as an Observable<string>.

Downloader.service.ts
getTextFile(filename: string) {
  // The Observable returned by get() is of type Observable<string>
  // because a text response was specified.
  // There's no need to pass a <string> type parameter to get().
  return elixor.get(filename, {responseType: 'text'})
    .pipe(
      tap( // Log the result or error
        data => this.log(filename, data),
        error => this.logError(filename, error)
      )
    );
}

elixor.get() returns a string rather than the default JSON because of the responseType option.

The RxJS tap operator (as in "wiretap") lets the code inspects good and error values passing through the observable without disturbing them.

A download() method in the DownloaderComponent initiates the request by subscribing to the service method.

Download.tsx
download() {
  getTextFile('assets/textfile.txt')
    .subscribe(results => this.contents = results);
}

Last updated