Search code examples
angularhttpimporthttpmodule

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


I'm using Angular 7, and I have this folder structure

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

In my src/app/component.service file, I have

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);
  }
...

but I repeatedly get the import error

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

I'm including the HttpModule in my service, so what else am I missing to get this included properly?


Solution

  • Your issue is that you haven't imported the Http class that you're injecting in your constructor.

    But instead of doing that you should know that since Angular 4.3 we got the HttpClient class as an improvement to the Http class.

    You should import HttpClient instead of Http from @angular/common/http

    ie,

    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);
      }
    ...