【问题标题】:Call a page function from Provider in Ionic 2在 Ionic 2 中从 Provider 调用页面函数
【发布时间】:2018-10-30 23:50:35
【问题描述】:

我在提供程序中有一个Observable.timer,我将其导入到特定页面。计时器结束时如何调用位于页面内而不是提供程序中的函数?

我现在正在做的是尝试在计时器使用.finally(() => this.endT()) 从提供程序结束时返回一个值,但它不起作用

页面

  import { TimerProvider } from '../../providers/timer/timer';

  endTimer() {
    console.log('timer ended');
  }

  newTimer() {
    this.countDown = this.timerProvider.newTimer();
    if(this.countDown == 'timer complete'){
      this.endTimer();
    }
  }

提供者

  countDown: any;
  counter = 1*100;
  tick = 1000;

  constructor(public http: HttpClient) {
    //console.log('Hello TimerProvider Provider');
  }

  newTimer() {
     return Observable.timer(0, this.tick).take(this.counter)
     .map(() => --this.counter).finally(() => this.endT());
  }

  endT() {
    return 'timer complete';
  }

【问题讨论】:

    标签: angular ionic-framework ionic2


    【解决方案1】:

    我以前遇到过这个问题。在 JavaScript/Typescript 中有一个简单的解决方案:回调函数

    JavaScript 允许您将函数传递给另一个函数,如下所示:

    您的页面

    myCallback() {
        console.log('finished');
    }
    
    myFunction() {
        // i'm calling my other function right here
        anotherFunction(myCallback);
    }
    

    您的提供商

    anotherFunction(callback) {
        // check if a callback is passed
        if (callback) {
            // execute your callback function whenever you want
            callback();
        }
    }
    

    您甚至可以向回调函数提供数据。你可能从Promises知道这个概念。

    【讨论】:

    • 不清楚如何将它从提供者传递到页面?你是说函数是这样发送的 thisFunction(callback()); ..
    • 你用newTimer()启动你的定时器,你可以将你的函数endTimer()传递给这样的函数:newTimer(endTimer)。在你的 newTimer 函数中,你可以像这样执行它:endTimer(),只要你想。
    【解决方案2】:

    一种方法是在提供程序中使用EventEmitter,它会在计时器结束时发出一些东西。在使用它的组件中,您订阅它。这是使用响应式模式编写 Angular 应用程序时的常见模式。

    //provider
    public timerEvent = new EventEmitter();
    //...
    newTimer() {
      Observable.timer(0, this.tick).take(this.counter)
      .map(() => --this.counter)
      .finally(() => this.timerEvent.emit(null));
    }
    
    //component
    newTimer() {
      this.timerProvider.timerEvent.subscribe( () => {
        //will be called when the timer from the providers ends
      });
      this.timerProvider.newTimer();
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-08
      • 2016-07-06
      • 2017-05-05
      • 1970-01-01
      • 2017-08-18
      • 2017-06-29
      • 1970-01-01
      • 1970-01-01
      • 2017-06-29
      相关资源
      最近更新 更多