1

Is there any way to check for network in background in Ionic2? Whenever the network is gone need to show message like Youtube? Currently i am following the below method, which is invoked before the api call.

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

Edited Question

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

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

i have written the above inside this.platform.ready().then(() => {}

Second Edit : Added 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);
//   }

}

Dak
  • 312
  • 2
  • 10
  • I think you can find the answer to your question in the referenced post. Let me know if that is not exactly what you were looking for and I'll reopen the post. Thanks :) – sebaferreras Sep 14 '17 at 06:21
  • @sebaferreras, where should I write those codes? in app.component.ts right? – Dak Sep 14 '17 at 06:29
  • Most of the code is the `NetworkService `, so it should be a new provider. The subscriptions at the end should be in the `app.component.ts` file – sebaferreras Sep 14 '17 at 06:37
  • Let me check and will update you – Dak Sep 14 '17 at 06:44
  • Can we invoke webservice based on this? – Dak Sep 14 '17 at 06:55
  • @sebaferreras Its not showing the toast – Dak Sep 14 '17 at 07:16
  • It's hard to know where the issue is without seeing your code. The code from the answer works properly and shows the toast. Please make sure you're doing the same on your end. – sebaferreras Sep 14 '17 at 07:19
  • Yeah, please find the edited question. I have added your codes to NetworkService .ts and added to app.module.ts then in app.component.ts i have added the code which is shone above – Dak Sep 14 '17 at 07:21
  • @sebaferreras After the app is launched I turned off the wifi/ mobile data, its not showing the toast and vice versa – Dak Sep 14 '17 at 07:35
  • Could you please add the entire `app.component.ts` file? – sebaferreras Sep 14 '17 at 07:59
  • @sebaferreras, Could you please tell me from where you are invoking the " initializeNetworkEvents " in NetworkService.ts file? Is it a built in function? – Arj 1411 Sep 14 '17 at 11:58
  • Call the `initializeNetworkEvents` method in your `app.component.ts` file, right after this line: `this.networkCheck();` – sebaferreras Sep 14 '17 at 12:11
  • let me check... – Dak Sep 14 '17 at 12:14
  • 1
    @sebaferreras,Hi Its works perfect. Thanks for the link. Just one more doubt. Is it possible to disable all the events like click, swipe etc and a show a no network page? – Dak Sep 15 '17 at 02:33
  • Glad to hear that! Hmmm, I think it could be done. Would you mind creating another question with some more details, so I can help you out there? :) – sebaferreras Sep 15 '17 at 07:13

0 Answers0