3
votes

I'm using Ionic 3 and I have made a class for globals variables but I get this error

Uncaught (in promise): Error: No provider for Globals! Error: No provider for Globals! at injectionError 
(http://localhost:8100/build/vendor.js:1590:86) at noProviderError 

This is the news.ts file

import {Globals} from "../../app/globals";

constructor(private globals: Globals, public navCtrl: NavController, public navParams: NavParams, private http: Http) {

    this.getData();
}

getData()
{
  this.http.get(this.globals.baseUrl + 'articles').map(res => res.json()).subscribe(data => {
      this.results = data;
      console.log(data)
  });
}

and I have tried to import in the app.mudule in the providers but get another error:

Encountered undefined provider! Usually this means you have a circular dependencies (might be caused by using 'barrel' index.ts files.

this is the app.module.ts file , Globals is imported but not declared in providers:

import {NgModule, ErrorHandler} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {IonicApp, IonicModule, IonicErrorHandler} from 'ionic-angular';
import {MyApp} from './app.component';
import {Globals} from 'globals';

import {TabsPage} from '../pages/tabs/tabs';
import {NewsPage} from '../pages/news/news';

import {StatusBar} from '@ionic-native/status-bar';
import {SplashScreen} from '@ionic-native/splash-screen';
import { HttpModule } from '@angular/http';

import {enableProdMode} from '@angular/core';
enableProdMode();

@NgModule({
   declarations: [
    MyApp,
    TabsPage,
    NewsPage
],
imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpModule
],
bootstrap: [IonicApp],
entryComponents: [
    MyApp,
    TabsPage,
    NewsPage
],
providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
]
})
export class AppModule {
}

This the file globals.ts :

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


@Injectable()
export class Globals {
   baseUrl: string = 'http://127.0.0.1/rest/web/app_dev.php/api/';
   uploadRootDir: string = 'http://localhost/rest/web/';
}
1
Do you have barrel file?Sampath
Can you show the code of app.module.ts file?Sampath
@Sampath This is the first application with ionic , I don't know what is barrel file , I have updated my question.hous
Can you show the Globals file?Sampath
yes, it's updatedhous

1 Answers

4
votes

You don't need to use provider for this.Just create Globals.ts file as shown below.

 export class Globals
        {
           static readonly baseUrl: string = 'http://127.0.0.1/rest/web/app_dev.php/api/';
           static readonly uploadRootDir: string = 'http://localhost/rest/web/';
        };

When you need to use it just import it like below and use it.

myPage.ts

import {Globals} from "../../app/globals";

myMethod(){
    console.log(Globals.baseUrl);
}