Convert Rxjs code to Angular 6 and latest rxjs

s-a-n

Scenario :

  • New to Angular
    Trying to migrate Angular 2 code into Angular 6.
  • Any idea how I can rewrite the following code in angular 6


Code To write in Angular 6 :

return this._http.post(this.apiBaseUrl + "/api/login", body, options)
   .timeoutWith(Constant.timeout, Observable.throw(new Error(Constant.timeoutMsg)))
      .map(response => {
            const result = response.json() as LoginResultModel;

            if (result.AccessToken != null) {
                this.setLoginToken(result);
                return result;
            } else {
                return response;
            }
        });
Martin Adámek

Just use pipe method and put both timeoutWith and map operators as functions as its parameters:

import { throwError } from 'rxjs';
import { map, timeoutWith } from 'rxjs/operators';

return this._httpClient.post<LoginResultModel>(this.apiBaseUrl + "/api/login", body, options)
  .pipe(
    timeoutWith(Constant.timeout, throwError(new Error(Constant.timeoutMsg))),
    map(result => {
      if (result.AccessToken != null) {
        this.setLoginToken(result);
        return result;
      } else {
        return response;
      }
    })
  );

More about pipable operators in RxJS 6:

https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md

Note I also used HttpClientModule, where you don't need to use response.json() method, more about that here:

https://angular.io/guide/http

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive