StaticInjectorError(AppModule) Error

17,651

Solution 1

I did not specify the type returned in getProducts() method of ProductProvider so http client assumed it was an object being returned and that caused the error. I was able to fix it by adding any[] to http get like this return this.http.get<any[]>('/assets/data.json')

Solution 2

You can generate the provider with the command:

ionic g provider <provider_name>

Ionic CLI will generate all the necessary things

Share:
17,651
Mena
Author by

Mena

Updated on June 30, 2022

Comments

  • Mena
    Mena almost 2 years

    I only just started learning how to work with Angular 2 and Ionic 3.20.0 but now facing a challenge. I'm trying to display product images in my home page but the app is throwing this error

    ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[HomePage -> ProductProvider]

    I have imported the ProductProvider service and added it to providers in my app.module.ts file.

    import { ProductProvider } from '../providers/product/product';
    
    @NgModule({
    ...  
    providers: [
      StatusBar,
      SplashScreen,
      {provide: ErrorHandler, useClass: IonicErrorHandler},
      ProductProvider
    ]
    

    Now this is the products.ts and home.ts files respectively

    product.ts

    import { HttpClient } from '@angular/common/http';
    import { Injectable } from '@angular/core';
    import 'rxjs/add/operator/map';
    
    @Injectable()
    export class ProductProvider {
    
    constructor(public http: HttpClient) {
      console.log('Hello ProductProvider Provider');
    }
    
    getProducts(){
       return this.http.get('/assets/data.json')
         .map(response => response);
    }
    }
    

    home.ts

    import { Component } from '@angular/core';
    import { NavController } from 'ionic-angular';
    import { Http } from '@angular/http';
    import "rxjs/add/operator/map";
    import { ProductProvider } from '../../providers/product/product';
    
    @Component({
      selector: 'page-home',
      templateUrl: 'home.html'
    })
    export class HomePage {
    public allProducts = [];
    
    constructor(private productProvide: ProductProvider, private http: Http, 
    public navCtrl: NavController) {
    
    }
    
    ionViewDidLoad(){
        this.productProvide.getProducts()
          .subscribe((response) => {
        this.allProducts = response;
    });
    }
    }
    

    Why is my code throwing this error?