使用Ionic 3的全局变量时出错

时间:2017-08-09 16:44:18

标签: angular typescript ionic-framework ionic3

我使用Ionic 3并且我为全局变量创建了一个类,但是我收到了这个错误

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 

这是 news.ts 文件

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)
  });
}

我尝试在提供商的 app.mudule 中导入,但又收到了其他错误:

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

这是 app.module.ts 文件,Globals已导入但未在提供商中声明:

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

这是文件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 个答案:

答案 0 :(得分:4)

您无需使用provider即可。只需创建Globals.ts文件,如下所示。

 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/';
        };

当您需要使用import时,如下所示并使用它。

myPage.ts

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

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