Ionic 2(使用Angular 2) - 如何访问另一个页面的功能?

时间:2017-01-09 22:41:10

标签: angular ionic-framework ionic2

我是Ionic和Angular 2的新手:

我试图创建一个服务(或Ionic 2中的提供者),它将保存我的全局变量和全局函数。

当我尝试在我的服务文件中导入AlertController和LoadingController(通过我的服务文件的构造函数实例化并在我的某个服务文件的函数上调用它的方法)时,我会收到错误消息“没有提供者为AlertController”等。

所以,我想 - 我可以创建一个名为“CommonFunctions”的页面,我可以将其用作我的服务/提供者函数的包装器 - 这样我就可以分离数据函数和UI函数(AlertContorller等)。 See this diagram

我现在收到错误消息“没有CommonFunctions的提供者”。我将CommonFunctions声明为普通页面,但我猜我不能在另一个页面上使用CommonFunctions函数?

所以我目前的选择(我能想到的是):

  1. 如何调用AlertController / LoadingController(或控制器等) 在服务/提供商中

  2. 如何使用其他页面的功能

  3. 如果这些都不可能,我想我必须接受我 无法在服务上调用AlertController / LoadingController函数 (这也意味着很多代码重复)。

  4. 非常感谢任何帮助。

    exercise.ts是用户看到的主页

    import { Component } from '@angular/core';
    import { NavController, LoadingController } from 'ionic-angular';
    import { FirebaseListObservable , FirebaseObjectObservable} from 'angularfire2';
    import { Common } from '../common/common'; 
    
    @Component({
      selector: 'page-exercise',
      templateUrl: 'exercise.html'
    })
    export class ExercisePage {
    
      public FBexercises: FirebaseListObservable<any[]>;
    
      constructor(
          public navCtrl: NavController,
          public loadingCtrl: LoadingController,
          public common: Common
        ) {
        this.getFBexercises();
      }
    
      getFBexercises(){
        let that = this;
    
          this.common.getFBLUL().then(function(){
          that.exerciseLUL = this.glob_var.exerciseLUL;
          that.exerciseLUL_backup = this.glob_var.exerciseLUL_backup;
          that.muscleGroupLUL = this.glob_var.muscleGroupLUL;
          that.muscleLUL = this.glob_var.muscleLUL;
        });
      }
    
      ionViewDidLoad() {
        console.log('Exercise Page Loaded');
      }
    
    
    }
    

    common.ts是一个页面,但我打算用它来存储我的全局函数

    import {Component, Injectable} from '@angular/core';
    import {GlobalVars} from '../../providers/global-vars';
    import {NavController, AlertController, LoadingController } from 'ionic-angular';
    
    @Component({
      selector: 'page-common',
      templateUrl: 'common.html'
    })
    
    @Injectable()
    export class Common {
    
        public static navCtrl: NavController
        public static alertCtrl: AlertController
        public static loadingCtrl : LoadingController
        public static globalVars: GlobalVars
    
        constructor () {
        }
         //creates loading bar
        createLoadingBar(message){
            return this.loadingCtrl.create({
              content: message
            });
        }
    
        getFBLUL(){
            let that = this;
            return new Promise(function(resolve, reject){
                  //create loading bar
                var loadingBar = that.createLoadingBar('Exercise List loading');
                loadingBar.present();
                that.globalVars.FBexercisesToLUL().then(function(){
                    loadingBar.dismiss();
    
              //TO-DO, receive exerciseLUL from FBexerciseToLUL() and return it when promise finishes
    
                    resolve();
                });
            });
        }
    }
    

    global-vars.ts是我用来从firebase数据库中获取数据的数据服务

    import {Injectable} from '@angular/core';
    import {AngularFire, FirebaseListObservable } from 'angularfire2';
    import 'rxjs/add/operator/map'
    
    @Injectable()
    export class GlobalVars {
    
      public muscleGroupLUL = [];
      public muscleLUL = [];
      public exerciseLUL = [];
      public exerciseLUL_backup = [];
    
      public FB_exercise: FirebaseListObservable<any[]>;
    
      constructor(
        public af: AngularFire
        ) {
        this.getFBexercise();
      }
    
      getFBexercise() {
        console.log("Getting FB Exercises");
        this.FB_exercise = this.af.database.list('/Exercise');
      }
    
      FBexercisesToLUL() {
        let that = this;
        return new Promise(function(resolve, reject){
            that.muscleGroupLUL.push("");
            that.muscleLUL.push("");
    
            that.FB_exercise.subscribe(exercises => {
              console.log("Exercises Loaded");
                // items is an array
    
                exercises.forEach(FBexercise => {
    
                var ref = FBexercise.$key;
                  var muscleGroup = FBexercise.body_part_name;
                  var muscle = FBexercise.muscle_name;
                  var exercise = FBexercise.exercise_name;
    
                if (that.muscleGroupLUL.indexOf(muscleGroup) === -1) { //if not in LUL
                    that.muscleGroupLUL.push(muscleGroup);
                }
                    if (that.muscleLUL.indexOf(muscle) === -1) { //if not in LUL
                    that.muscleLUL.push(muscle);
                }
                if (that.exerciseLUL.indexOf(exercise) === -1) { //if not in LUL
                    that.exerciseLUL.push({ref:ref, exercise: exercise, muscle : muscle, muscleGroup : muscleGroup});
                }
    
              });
    
              that.exerciseLUL_backup = that.exerciseLUL;
    
          //TO-DO, return exerciseLUL when promise finishes 
    
              resolve();
    
          });
        });
      }
    }
    

1 个答案:

答案 0 :(得分:0)

您收到此错误是因为您必须在使用之前声明提供程序。

有一个提供者声明的例子:

@NgModule({
   ...
   providers: [
       MyService
   ]
})

您的服务类应使用@Injectable()进行修饰。

@Injectable()
export class MyService {
   ...
}

然后,您可以将此服务注入任何组件的构造函数。

@Component({
    ...
})
export class MyComponent {
    constructor(serviceVariable: MyService) {
        serviceVariable.someMethod();
    }
}