我为什么得到“ src / app / component.service.ts(9,29)中的错误:错误TS2304:找不到名称'Http'。”在角度?

时间:2019-05-20 17:07:33

标签: angular http import httpmodule

我正在使用Angular 7,并且具有此文件夹结构

src
    app
        app.component.css  
        app.component.html  
        app.component.spec.ts  
        app.component.ts    
        app.module.ts  
        component.service.spec.ts  
        component.service.ts

在我的src / app / component.service文件中,

import { Injectable } from '@angular/core';
import { HttpModule } from '@angular/http';

@Injectable({
  providedIn: 'root'
})
export class ComponentService {
  private apiUrl = 'http://localhost:8080/todo/';
  constructor(private http: Http) {
  }

  findAll(): Promise<Array<AppComponent>> {
    return this.http.get(this.apiUrl + "/list")
      .toPromise()
      .then(response => response.json() as Todo[])
      .catch(this.handleError);
  }
...

但是我反复遇到导入错误

ERROR in src/app/component.service.ts(9,29): error TS2304: Cannot find name 'Http'.

我在服务中包含了HttpModule,那么我还缺少什么才能使它正确包含?

1 个答案:

答案 0 :(得分:1)

您的问题是您尚未导入要在构造函数中注入的Http类。

但是,您应该知道自Angular 4.3以来,我们得到了HttpClient类作为Http类的改进。

您应该从HttpClient导入Http而不是@angular/common/http

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ComponentService {
  private apiUrl = 'http://localhost:8080/todo/';
  constructor(private http: HttpClient) {
  }

  findAll(): Promise<Array<AppComponent>> {
    return this.http.get(this.apiUrl + "/list")
      .toPromise()
      .then(response => response.json() as Todo[])
      .catch(this.handleError);
  }
...