Ionic 2 How to use Cordova events pause resume

2019-01-25 09:16发布

I am surprised to not find any thread already created on that topic.

In Ionic 2 there is the lifecycle of the pages in NavController: ionView[didLoad|didLeave|...]

And there are the Cordova events that are supposed to be called like this: document.addEventListener("pause", onPause, false);

I am in a situation where I want to get the Cordova events. Ionic lifecylce of pages is not a fit because what I want to do need to happen when the device gets in the onResume status whichever page shows on.

I haven't tried it yet, because I was hoping to find a good lead here before to keep on going, but I have the feeling that document won't be accessible from Angular2, Ionic2 and that I will probably will have to add a service to access the window like it is explained here.

Or is there anyother known way to access document.addEventListener(...) when in Ionic 2?

2条回答
forever°为你锁心
2楼-- · 2019-01-25 10:06

The way it works in Ionic 2 is detailed here

Basically, you need to inject the Platform instance in your page and subscribe to the pause event emitter:

import { Component } from '@angular/core';
import { Subscription } from 'rxjs';
import { Platform } from 'ionic-angular';

@Component({...})
export class AppPage {
  private onResumeSubscription: Subscription;

  constructor(platform: Platform) {
    this.onResumeSubscription = platform.resume.subscribe(() => {
       // do something meaningful when the app is put in the foreground
    }); 
  } 

  ngOnDestroy() {
    // always unsubscribe your subscriptions to prevent leaks
    this.onResumeSubscription.unsubscribe();
  }
}
查看更多
Bombasti
3楼-- · 2019-01-25 10:10

I was also able to get document.addEventListener working from the constructor method of an Ionic2 page e.g.

  document.addEventListener("pause", function() {
    // do something
  }, true);

  document.addEventListener("resume", function() {
    // do something
  }, true);
查看更多
登录 后发表回答