【问题标题】:Why do I get "ERROR in src/app/component.service.ts(9,29): error TS2304: Cannot find name 'Http'." in angular?为什么我会收到“src/app/component.service.ts(9,29) 中的错误:错误 TS2304:找不到名称 'Http'。”在角度?
【发布时间】:2019-05-20 17:07:33
【问题描述】:

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

【问题讨论】:

    标签: angular http import httpmodule


    【解决方案1】:

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

    但是你应该知道,从 Angular 4.3 开始,我们得到了 HttpClient 类作为对 Http 类的改进,而不是这样做。

    您应该从@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);
      }
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-07
      • 2019-11-30
      • 1970-01-01
      • 2019-08-17
      • 1970-01-01
      • 2015-05-29
      • 2016-12-18
      • 2019-05-06
      相关资源
      最近更新 更多