如何在Youtube for Ionic2等背景下进行网络检查

时间:2017-09-14 06:10:06

标签: typescript ionic2

有没有办法在Ionic2中检查后台网络?每当网络消失,需要显示Youtube等消息吗? 目前我遵循以下方法,该方法在api调用之前调用。

isOnline() {
    if (navigator.onLine) {
        return true;
    } else {
        return false;
    }
}

已编辑的问题

networkCheck(){
    this.eventCtrl.subscribe('network:online',()=>{
        this.genericService.showToast("Network Available");
    });

    this.eventCtrl.subscribe('network:offline',()=>{
         this.genericService.showToast("Network Gone");
    })
}

我在this.platform.ready().then(() => {}

内写了以上内容

第二次编辑:添加了app.component.ts

import { Component, ViewChild, OnInit } from '@angular/core';
import { Platform, MenuController, Nav, IonicApp, } from 'ionic-angular';
import { LoginTemplate } from '../pages/login-Module/login.component';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { TranslateService } from 'ng2-translate';
import { GenericServices } from "../webservices/generic-services";
import { Network } from "@ionic-native/network";
import { Events } from 'ionic-angular';

@Component({
    templateUrl: 'app.html',
})
export class MyApp implements OnInit {

@ViewChild(Nav) nav: Nav;
defaultLng: any = "";
timer: any;
counter: number = 0;
ngOnInit(): void {
    this.translate.addLangs(["en", "ml"]);
    this.defaultLng = this.translate.setDefaultLang("en");
    this.translate.use(this.translate.getBrowserLang().match(/en|ml/) ? this.translate.getBrowserLang() : this.defaultLng);
    //this.translate.use(this.defaultLng);
}
rootPage = LoginTemplate;
//rootPage = AddLinesComponent;
//pages: Array<{ title: string, component: any }>;

constructor(
    public platform: Platform,
    public menu: MenuController,
    public statusBar: StatusBar,
    public splashScreen: SplashScreen,
    public translate: TranslateService,
    public ionicApp: IonicApp,
    public genericService: GenericServices,
    private network: Network,
    private eventCtrl:Events) {
    this.initializeApp();
}

initializeApp() {
    this.platform.ready().then(() => {
        // Okay, so the platform is ready and our plugins are available.
        // Here you can do any higher level native things you might need.
        this.statusBar.styleDefault();
        this.splashScreen.hide();
        // Write code for push notifications here

        //Continuous check for network
       this.networkCheck();
        //Launch the last view 
        this.platform.resume.subscribe(() => {
            const lastState = localStorage.getItem("lastState"); //GET THE LATEST STATE, YOU'LL ALWAYS HAVE ONE BE CAUSE THE APP'LL ALWAYS PAUSE
            clearInterval(this.timer); // CLEAR THE INTERVAL
            if (this.counter < 900000) {// IF IT'S UNDER NEEDED TIME. 900000 == 15 min
                console.log("inside timer")
                this.nav.setRoot(lastState);
            }
            else {
                console.log("inside timer else")
                this.nav.popToRoot();
            }

        });

        //Application paused when moved to background
        this.platform.pause.subscribe(() => {
            console.log('[INFO] App Paused.');
            localStorage.setItem("lastState", this.nav.last().name);
            this.timer = setInterval(() => {
                this.counter += 50;
            }, 50);
        });


        //to handle the back button action
        this.platform.registerBackButtonAction(() => {
            let activePortal = this.ionicApp._loadingPortal.getActive() ||
                this.ionicApp._modalPortal.getActive() ||
                this.ionicApp._toastPortal.getActive() ||
                this.ionicApp._overlayPortal.getActive();
            if (activePortal) {
                activePortal.dismiss();
            } else {
                if (this.nav.canGoBack()) {
                    this.nav.pop();
                } else {
                    if (this.nav.getActive().name === "LoginTemplate") {
                        this.platform.exitApp();
                    } else {
                        this.genericService.showAlert("Exit", "Do you want to exit the app?", this.onYesHandler, this.onNoHandler, "backPress");
                    }
                }
            }

        });
    });
}
networkCheck(){
    this.eventCtrl.subscribe('network:online',()=>{
        this.genericService.showToast("Network Available");
    });

    this.eventCtrl.subscribe('network:offline',()=>{
         this.genericService.showToast("Network Gone");
    })
}

/*--------Alert Cal Back------*/
onYesHandler = (caller) => {
    if (caller == "backPress") {
        this.platform.exitApp();
        localStorage.clear();
    }
}
onNoHandler = (caller) => {
    if (caller == "backPress") {

    }
}

//   openPage(page) {
//     // close the menu when clicking a link from the menu
//    // this.menu.close();
//     // navigate to the new page if it is not the current page
//  //   this.nav.setRoot(page.component);
//   }

}

0 个答案:

没有答案