您好,我的代码有问题。
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
你能帮帮我吗?谢谢
最佳答案
如其他人所述,Http
已弃用,请改用 HttpClient
。 HttpClient
解析您对对象的响应,因此您删除响应的映射。另外,要避免 type checking errors ,告诉 Angular 你期望什么样的响应。
因此导入 HttpClientModule
并将其添加到 imports 数组中,在 BrowserModule
之后。在您的服务导入 HttpClient
中,将其注入(inject)您的构造函数并按以下方式使用它:
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)
}
}
关于javascript - Angular 4 this.http.get(...).map 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47916920/