No provider for Http StaticInjectorError

Drew picture Drew · Nov 26, 2017 · Viewed 176.4k times · Source

I am trying to pull the data from my api, and populate it in my ionic app, but it is crashing when I enter the page the data should be populated on. Below are my two .ts files:

import { Component } from '@angular/core';

import { NavController, LoadingController } from 'ionic-angular';
import { RestService } from '../../providers/rest-service/rest-service';

@Component({
  selector: 'page-all-patients',
  templateUrl: 'all-patients.html',
  providers: [RestService]
})
export class AllPatientsPage {
  data: any;
  loading: any;

  constructor(public navCtrl: NavController, public restService: RestService, public loadingCtrl: LoadingController) {

    this.loading = this.loadingCtrl.create({
      content: `
        <ion-spinner></ion-spinner>`
    });
    this.getdata();
  }

  getdata() {
    this.loading.present();
    this.restService.getJsonData().subscribe(
      result => {
        this.data=result.data.children;
        console.log("Success: " + this.data);
      },
      err => {
        console.error("Error : " + err);
      },
      () => {
        this.loading.dismiss();
        console.log('getData completed');
     }
   );
 }
}

and the other file:

import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';

/*
  Generated class for the RestServiceProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/

@Injectable()
export class RestService {

  constructor(public http: Http) {
    console.log('Hello RestServiceProvider Provider');
  }

  getJsonData() {
    // return Promise.resolve(this.data);

     return this.http.get('url').map(res => res.json());
   }

}

I have tried using the HttpModule as well, but it is a fatal error. The error is as shows:

Error: Uncaught (in promise): Error: StaticInjectorError[Http]: 
  StaticInjectorError[Http]: 
    NullInjectorError: No provider for Http!
Error: StaticInjectorError[Http]: 
  StaticInjectorError[Http]: 
    NullInjectorError: No provider for Http!
    at _NullInjector.get (http://lndapp.wpi.edu:8100/build/vendor.js:1276:19)

I am unsure why there is a no provider error, as this is the provider created through ionic framework

Answer

Sajeetharan picture Sajeetharan · Nov 26, 2017

In order to use Http in your app you will need to add the HttpModule to your app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ErrorHandler } from '@angular/core';
import { HttpModule } from '@angular/http';
...
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot()
  ]

EDIT

As mentioned in the comment below, HttpModule is deprecated now, use import { HttpClientModule } from '@angular/common/http'; Make sure HttpClientModule in your imports:[] array