Angular 4 this.http.get(...).map 不是函数

Angular 4 this.http.get(...).map is not a function

您好,我的代码有问题。

import { Injectable } from '@angular/core';
import { Car } from "./models/car";
import { Observable } from "rxjs/Observable";
import { Http } from "@angular/http";
import 'rxjs'

@Injectable()
export class CarsService {
   private apiUrl = "http://localhost:3000/api/cars";
   constructor(private http : Http) { }

    getCars() : Observable<Car[]> {
        return this.http.get(this.apiUrl)
           .map((res) => res.json())
    }
}

使用此代码我有错误:

this.http.get(...).map is not a function

但是当我添加:

import 'rxjs/add/operator/map'

仍有问题,但错误是:

Cannot read property 'map' of undefined

你能帮帮我吗?谢谢

使用 angular5 HttpClient 实现已经包括内部使用 map.so 它会自动为您工作。

更新为

 getCars() : Observable<Car[]> {
     return this.http.get(this.apiUrl)
 }

还要确保您使用的是 HttpClient 而不是 Http.

您可以阅读更多相关信息 here

编辑您的代码

import { Injectable } from '@angular/core';
import { Car } from "./models/car";
import { Observable } from "rxjs/Observable";
import { Http } from "@angular/http";


@Injectable()
export class CarsService {
   private apiUrl = "http://localhost:3000/api/cars";
   constructor(private http : Http) { }

   getCars() : Observable<Car[]> {
     return this.http.get(this.apiUrl)
   }
}

因为它会自动将响应解析为 JSON。您不必显式解析它。

如其他人所述,Http 已弃用,请改用 HttpClientHttpClient 解析您对对象的响应,因此您删除了响应的映射。另外,为了避免 type checking errors,请告诉 Angular 您期望得到什么样的响应。

所以导入 HttpClientModule 并将其添加到导入数组中,在 BrowserModule 之后。在您的服务导入 HttpClient 中,将其注入您的构造函数并按以下方式使用它:

import { Injectable } from '@angular/core';
import { Car } from "./models/car";
import { Observable } from "rxjs/Observable";
import { HttpClient } from "@angular/common/http";
import 'rxjs'

@Injectable()
export class CarsService {
   private apiUrl = "http://localhost:3000/api/cars";
   constructor(private httpClient : HttpClient) { }

    getCars() : Observable<Car[]> {
      // tell Angular you are expecting an array of 'Car'
      return this.httpClient.get<Car[]>(this.apiUrl)
    }
}
ngOnInit() {
 this.loadCars();

}

loadCars() : void {
 this.carsService.getCars().subscribe((cars) => {
  this.cars = cars;
  this.countTotalCost();
 })
}

所以我移动这个this.countTotalCost();

ngOnInitloadCars

现在 .map 没问题了。

我只有这个错误:检查后表达式已更改。先前值:'undefined'。当前值:'NaN'.

<div class="row" *ngIf="grossCost"> //this line error/error context
 <div class="col-sm-12">
  <div class="total-cost">
   <p class="text-right">TOTAL GROSS COST: {{ grossCost}} PLN</p>
  </div>
 </div>
</div>