No provider for Http StaticInjectorError

AngularTypescriptIonic Framework

Angular Problem Overview


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

Angular Solutions


Solution 1 - Angular

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

Solution 2 - Angular

Update: Angular v6+
For Apps converted from older versions (Angular v2 - v5): HttpModule is now deprecated and you need to replace it with HttpClientModule or else you will get the error too.

  1. In your app.module.ts replace import { HttpModule } from '@angular/http'; with the new HttpClientModule import { HttpClientModule} from "@angular/common/http"; Note: Be sure to then update the modules imports[] array by removing the old HttpModule and replacing it with the new HttpClientModule.

  2. In any of your services that used HttpModule replace import { Http } from '@angular/http'; with the new HttpClient import { HttpClient } from '@angular/common/http';

  3. Update how you handle your Http response. For example - If you have code that looks like this

    http.get('people.json').subscribe((res:Response) => this.people = res.json());

The above code example will result in an error. We no longer need to parse the response, because it already comes back as JSON in the config object.

> The subscription callback copies the data fields into the component's config object, which is data-bound in the component template for display.

For more information please see the - Angular HttpClientModule - Official Documentation

Solution 3 - Angular

You would need also to import the HttpClientModule from Angular '@angular/common/http' into your main AppModule for making HTTP requests.

app.module.ts

import { HttpClientModule } from '@angular/common/http';
import { ServiceService } from '../../../services/service.service';

@NgModule({
   imports: [
       HttpClientModule
   ],
   providers: [
       ServiceService
   ]
})
export class AppModule {...}

Solution 4 - Angular

Add these two file in your app.module.ts

import { FileTransfer } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';

after that declare these to in provider..

providers: [
    Api,
    Items,
    User,
    Camera,
    File,
    FileTransfer];

This is work for me.

Solution 5 - Angular

I am on an angular project that (unfortunately) uses source code inclusion via tsconfig.json to connect different collections of code. I came across a similar StaticInjector error for a service (e.g.RestService in the top example) and I was able to fix it by listing the service dependencies in the deps array when providing the affected service in the module, for example:

import { HttpClient } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { RestService } from 'mylib/src/rest/rest.service';
...
@NgModule({
  imports: [
    ...
    HttpModule,
    ...
  ],
  providers: [
    {
      provide: RestService,
      useClass: RestService,
      deps: [HttpClient] /* the injected services in the constructor for RestService */
    },
  ]
  ...

Solution 6 - Angular

In ionic 4.6 I use the following technique and it works. I am adding this answer so that if anybody is facing similar issues in newer ionic version app, it may help them.

i) Open app.module.ts and add the following code block to import HttpModule and HttpClientModule

import { HttpModule } from '@angular/http';
import {   HttpClientModule } from '@angular/common/http';

ii) In @NgModule import sections add below lines:

HttpModule,
HttpClientModule,

So, in my case @NgModule, looks like this:

@NgModule({
  declarations: [AppComponent ],
  entryComponents: [ ],
  imports: [
    BrowserModule,
    HttpModule,
    HttpClientModule,
    IonicModule.forRoot(),
    AppRoutingModule, 
  ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})

That's it!

Solution 7 - Angular

I was trying to fix the issue for about an hour and just deiced to restart the server. Only to see the issue is fixed.

If you make changes to APP module and the issue remains the same, stop the server and try running the serve command again.

Using ionic 4 with angular 7

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDrewView Question on Stackoverflow
Solution 1 - AngularSajeetharanView Answer on Stackoverflow
Solution 2 - AngularNarmView Answer on Stackoverflow
Solution 3 - AngularGunjan KumarView Answer on Stackoverflow
Solution 4 - AngularRajiv PandeyView Answer on Stackoverflow
Solution 5 - AngulartedwView Answer on Stackoverflow
Solution 6 - AngularPhan HeroView Answer on Stackoverflow
Solution 7 - AngularLasithdsView Answer on Stackoverflow