Ricerca nel sito web

typescript - Angular 6 - rxjs proprietà 'map' non esiste sul tipo 'observable'


Ricevo questo errore quando ho aggiornato ad Angular 6. Vedo la documentazione per usare .pipe(), ma non capisco come usare pipe quando ci sono più .map() come di seguito. Ho bisogno del tuo aiuto...

   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;
          }));
      }
    }

Capisco di usare .pipe quando ce n'è uno .map usato come sotto, ma non riesco a capire come usare pipe() quando vengono usati più .map.

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

Risposta n. 1

per usare la pipe con più operatori dovresti usare la virgola:

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;
  })
);

ma non è necessario usare map(res => res.json()) nel tuo caso.

e

Nelle versioni precedenti l'importazione era import 'rxjs/add/operators/map'.

In Angular 6 dovrebbe essere: import { map } from 'rxjs/operators';

A proposito, se ti aspetti l'effetto di cancellazione, dovresti usare switchMap invece di map. Leggi di più