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

标签 javascript angular rxjs angular-http

您好,我的代码有问题。

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 已弃用,请改用 HttpClientHttpClient 解析您对对象的响应,因此您删除响应的映射。另外,要避免 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/

相关文章:

javascript - 卡在socket.io上

angular - Typescript,Angular - 如何在一段时间后重新加载网站

javascript - 函数链不工作 Angular 5

AngularFire根据用户身份验证检索文档ID

rxjs - switchMap里面的动态数组CombineLatest是不断退订再订阅

javascript - RxJS:锁定水平或垂直鼠标拖动

angular - SystemJS 为 rxjs 加载很多文件

javascript - 在对象构造函数中使用对象字面量符号的好处?

javascript - 预编译 application.js 资源

javascript - 使用 babel 编译多个文件