Angular 6 - rxjs property 'map' does not exist on type 'observable'

Viewed 4217

Getting this error when I upgraded to Angular 6. I see the documentation to use .pipe(), but I am not getting how to use pipe when there is multiple .map() as below. Need your help...

   import {Injectable} from '@angular/core';
    import {Http, Headers} from '@angular/http';
    import 'rxjs/add/operator/map';
    import {TOKEN_AUTH_PASSWORD, TOKEN_AUTH_USERNAME} from '../services/auth.constant';

    @Injectable()

    export class AuthenticationService {

      static AUTH_TOKEN = '/oauth/token';
      constructor(private http: Http) {
      }
      login(username: string, password: string) {

        const body = `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}&grant_type=password`;

        const headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        headers.append('Authorization', 'Basic ' + btoa(TOKEN_AUTH_USERNAME + ':' + TOKEN_AUTH_PASSWORD));
        return this.http.post(AuthenticationService.AUTH_TOKEN, body, {headers})
          //.map(res => res.json())
          .pipe(map((res: any) => {
            if (res.access_token) {
              return res.access_token;
            }
            return null;
          }));
      }
    }

I understand to use .pipe when there is one .map is used like below, but I am not getting how to use pipe() when multiple .map are used.

.pipe(map(data => {})).subscribe(result => {
      console.log(result);
    });
1 Answers

to use pipe with multiple operators you should use comma:

return this.http.post(AuthenticationService.AUTH_TOKEN, body, {headers})
.pipe(
  map(res => res.json()),
  map((res: any) => {
    if (res.access_token) {
      return res.access_token;
    }
    return null;
  })
);

but it's not needed to use map(res => res.json()) in your case.

and

In previous versions the import was import 'rxjs/add/operators/map'.

In Angular 6 it should be: import { map } from 'rxjs/operators';

By the way if you're expected the cancelling effect you should use switchMap instead of map. Read more

Related