[angular] No provider for Http StaticInjectorError

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

This question is related to angular typescript ionic-framework

The answer is


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!


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 {...}

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


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.


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 */
    },
  ]
  ...

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


Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to ionic-framework

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3 Xcode couldn't find any provisioning profiles matching No provider for Http StaticInjectorError Error: Cannot find module '../lib/utils/unsupported.js' while using Ionic Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator) Error: Node Sass does not yet support your current environment: Windows 64-bit with false Failed to find 'ANDROID_HOME' environment variable Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable ionic build Android | error: No installed build tools found. Please install the Android build tools