1. 程式人生 > >Angular5到Angular6:Property 'map' does not exist on type 'Observable'.

Angular5到Angular6:Property 'map' does not exist on type 'Observable'.

錯誤原因:angular6不再支援原來的Http,用HttpClient代替了原來的Http

解決方案:

1. import

import {Http, Headers, Response} from '@angular/http';  

改為=>

import {HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

2.constructor

constructor(
  private httpService: Http
) {}

改為=>

constructor(
  private httpClient: HttpClient
) {}

3.具體用法

const headers = new Headers({
  'Content-Type': 'application/json',
  'x-access-token': localStorage.getItem('token') ? localStorage.getItem('token') : ''
});
return this.httpService.get(environment.baseUrl + 'users/myheadshot',
  {headers: headers})
  .map((response: Response) => {
    return response.json();
  });

改為=>

const headers = new HttpHeaders({
  'Content-Type': 'application/json',
  'x-access-token': localStorage.getItem('token') ? localStorage.getItem('token') : ''
});
return this.httpClient.get<any>(environment.baseUrl + 'users/myheadshot', {headers: headers});

注意:在換成httpClient後,必須指定返回型別,不然會報錯,返回型別緊接get/post...之後,用尖括號括起來,比如httpClient.get<any>,當不知道返回型別是什麼時,用any。