K
K
Konstantin2018-10-26 00:52:09
Angular
Konstantin, 2018-10-26 00:52:09

HttpClient in Angular 6.7?

I decided to update Angular 2 to the latest version 7. A lot has changed, in particular the HTTP client.
How will the following code for sending a POST request look like in Angular 6.7?

public refresh(person: number): Observable<any> {
    const data = {
      '$type': 'ReadRequest',
      'query': 'refresh',
      'parameters': {'person': person}
    };

    return this.http.post(null, data)
      .map(res => (<any>res)._body === '' ? {} : res.json())
      .catch(this.handleError);
  }

Do I need `.map(res => (res)._body === '' ? {} : res.json())` and how to handle exceptions (errors)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Demian Smith, 2018-10-26
@Junart1

The post has the format post(url, body, options). In this regard, little has changed.
no longer needed.
HttpClient parses the response text as JSON by default. If the response text cannot be parsed, then an exception is thrown.
Errors are handled as before: catchError takes response: HttpErrorResponse as the first parameter. And returns observable.
Most likely you updated RxJS as well. They will remove (or have already removed) the call of chain operators. Now instead of

observable$
  .map()
  .switchMap()
  .catch()

you need to call pipe() and pass the necessary operators to it:
observable$.pipe(
  map(),
  switchMap(),
  catchError()
)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question