编程语言
首页 > 编程语言> > javascript – Angular 4 this.http.get(…).map不是函数

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

作者:互联网

嗨,我的代码有问题.

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会解析您对Object的响应,因此您可以删除响应的映射.另外,为了避免type checking errors,请告诉Angular您期待什么样的响应.

因此,在BrowserModule之后导入HttpClientModule并将其添加到imports数组.在您的Service导入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)
    }
}

标签:javascript,rxjs,angular,angular-http
来源: https://codeday.me/bug/20190527/1162793.html