为什么我在 angular 中得到 "ERROR in src/app/component.service.ts(9,29): error TS2304: Cannot find name 'Http'."?

Why do I get "ERROR in src/app/component.service.ts(9,29): error TS2304: Cannot find name 'Http'." in angular?

我正在使用 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,那么我还缺少什么来正确包含它?

你的问题是你没有导入你在构造函数中注入的 Http class。

但你应该知道,自从 Angular 4.3 以来,我们得到了 HttpClient class 作为对 Http class.[=16= 的改进,而不是这样做]

您应该从 @angular/common/http

导入 HttpClient 而不是 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);
  }
...