How to refresh a page when net connection established?

Friends,
I am using some form fields in a page . When I reach that page if Net connectivity lose show
error message. But when connectivity established I could not reuse that page without going backward. How to add a line of code to refresh that page when the condition in app.component.ts met as shown:

connectonchange=this.network.onchange().subscribe(() => {
                  switch (this.network.type) {
                  case '2g':
                    console.log('probably not very fast ...');
                    this.showToast("2G!");
                    break;
                  case 'wifi':
                    console.log('wohoo wifi ...');
                    this.showToast("WIFI");
                    break;
                    case 'none':
                    console.log('No network ...');
                    this.showToast("No Network");
                    //Experimental
                    //alert("ddTS: "+this.global1.navPage);
                    //this.synchronize();
                    break;
                    case '4g':
                    console.log('4G ...');
                    this.showToast("4G");
                    break; 
                    case '3g':
                    console.log('3G ...');
                    this.showToast("3G");
                    break;
                    case 'unknown':
                    console.log('unknown network ...');
                    this.showToast("unknown Network");
                    break;

                    //unknown, ethernet, wifi, 2g, 3g, 4g, cellular, none
                }
              });
 

suppose if check 4G how i refresh that page …

please advise

Thanks
Anes

@anespa I advise you to create a service and declare it in the AppModule. The service will listen to the changes in the network:

@Injectable()
export class NetworkService {

	private readonly REFRESH_TYPES = new Set(['4g', 'wifi']);
	private lastType: string = null;
	public refresh$ = this.network.onchange().pipe(
		filter(() => {
			const currentType = this.network.type;
			const changed = (this.lastType !== currentType);
			const refreshType = this.REFRESH_TYPES.has(currentType);
			const lastRefreshType = this.REFRESH_TYPES.has(this.lastType);
			const pass = this.lastType && changed && refreshType && (!lastRefreshType);
			this.lastType = currentType;
			return pass;
		}),
	);

	constructor(private network: Network) { }

}

You import the filter with import { filter } from 'rxjs/operators/filter'; (it’s a lettable/pipeable operator).

In the Set you define the types you want to refresh your pages (in this case, 4g and wifi). It will only pass the filter condition if the last type was not null (it was not the first change), the new type is different than the last one, the new type is a type in which you want to refresh your page (it’s 4g or wifi in this case and the last one is not a type to refresh the page).

Then in your page you subscribe to it:

public ngOnInit() {
	this.networkService.refresh$.subscribe(() => this.refresh());
}

In refresh you just refresh what you want in the page (maybe doing an http call).

If you want to keep a flag that indicates if you want to refresh (because if the page was already loaded, you don’t need to load it again, even if the network type changed):

private needRefresh: boolean = true;

public ngOnInit() {
	this.networkService.refresh$.pipe(filter(() => this.needRefresh)).subscribe(() => this.refresh());
}

private refresh() {
	// refresh your page (what you want to refresh)
	// Example
	this.http.get('my-url').subscribe(result => {
		this.needRefresh = false;
		// do the changes
	});
}

This is just a basic example. Then you just adapt it to your use case.

I will message you personally due to some actual code…

@anespa What doesn’t work? Do you receive the alert with the text inside refresh? Also, it may not be a good idea to show the loading because the network change event might not be caused by the user, leading to a bad UX (because the loading don’t let the user interact with the app).

But first see if the alert with the refresh is called.

You can put a log in the refresh filter to see if it returns correctly (it should return true when you want to refresh):

public refresh$ = this.network.onchange().pipe(
	filter(() => {
		const currentType = this.network.type;
		const changed = (this.lastType !== currentType);
		const refreshType = this.REFRESH_TYPES.has(currentType);
		const lastRefreshType = this.REFRESH_TYPES.has(this.lastType);
		const pass = this.lastType && changed && refreshType && (!lastRefreshType);
		console.log('pass', pass, changed, currentType, this.lastType);
		this.lastType = currentType;		
		return pass;
	}),
);

It go inside refresh . But not load the actual content . Fields are blank . please check the code in PM

I have no idea how to show that loading mechanism without destructing UX . Please advise

Anes

Then the problem is not in the refresh itself.

I think now you should give a look in your code, and put some logs to see what is returning from the server and what is received by your component.

When the following functions are returned you could call a next() in a subject (similar to what is done in the service with the refresh), one subject for each one of the following:

this.getYearMaster();      
this.getCategory();     
this.getSectorType();

Then in your component (ts file) you subscribe to it and update the template.

I can’t help you too much tough, that would require some time and I’m kind of busy right now, but what I explained above could give you a general idea.

Dear Lucas,

How i can implement a next() function one after the other ? Do you please give a sample ?

@anespa You sont implement it, you just call in the subject.

In your controller:

// import { Subject } from 'rxjs/Subject';
// change any to the object type to make the code more legible
private yearMasterSub$ = new Subject<any>();
private categorySub$ = new Subject<any>();    
private sectorTypeSub$ = new Subject<any>();

private yearMaster$ = this.yearMasterSub$.asObservable();
private category$ = this.categorySub$.asObservable();
private sectorType$ = this.sectorTypeSub$.asObservable();

Then in your function (still in your controller):

private getYearMaster() {
	//...
	this.httpCall(...).then(result => {
		this.yearMasterSub$.next(result);
	})
}

// the same applies to the other subscriptions

And finally in your page:

ngOnInit() {
	this.myController.yearMaster$.subscribe(yearMaster => this.yearMaster = yearMaster);
	// The same applies to the other subscriptions
	// Only subscribe for the values that you need in your page
	// Your variables can have different names though
	// I assumed a property yearMaster  that is used in your template (it may change according to your use case)
}

Dear Lucas,
My current problem is now a bit different . The ** Network Service ** provider correctly identify the disconnection and call the refresh function. In Refresh function got all the data . But that’s not populated in template. I think the template is loaded before the data available .

Do you please advise on the controller

import { Component, OnInit } from '@angular/core';
import { NavController, NavParams, AlertController, LoadingController } from 'ionic-angular';
import { ProjectplanProvider } from "../../providers/projectplan/projectplan";
import { NetworkServiceProvider } from "../../providers/network-service/network-service";
import {GlobalProvider} from "../../providers/global/global";
import { FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms';
import { Storage } from '@ionic/storage';
import { Subject } from 'rxjs/Subject';
// For network
//import { Network } from '@ionic-native/network';

/**
 * Generated class for the ProjectplanPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@Component({
  selector: 'page-projectplan',
  templateUrl: 'projectplan.html',
})
export class ProjectplanPage implements OnInit {
  formgroup:FormGroup;
  financialYear:AbstractControl;
  projectCategory:AbstractControl;
  projectSector:AbstractControl; 
  private yearMasterSub$ = new Subject<any>();
  private categorySub$ = new Subject<any>();    
  private sectorTypeSub$ = new Subject<any>();    
  private yearMaster$ = this.yearMasterSub$.asObservable();
  private category$ = this.categorySub$.asObservable();
  private sectorType$ = this.sectorTypeSub$.asObservable();
  data:any = {};
  result: any;
  resultdesc: any;
  searchFlag: boolean = false;
  connectivityFlag: boolean = false;
  selectedItem: boolean = false;
  year: any;
  public category: any=0;
  public sector: any=0;
  public lbid: number;
  public lbname: string;
  public distid: number;
  public lbtype: number;
  constructor(public navCtrl: NavController, public navParams: NavParams, 
              public projectplanprovider: ProjectplanProvider,
              public networkserviceprovider: NetworkServiceProvider,
              public formbuilder: FormBuilder,
              private alertCtrl: AlertController,
              public loadingController: LoadingController,
              public global1:GlobalProvider,
              private storage: Storage
              ) {
                this.formgroup = formbuilder.group({
                  financialYear:['',Validators.required],
                  projectCategory:['',Validators.required],
                  projectSector:['',Validators.required],
                });
                this.financialYear = this.formgroup.controls['financialYear'];
                this.projectCategory = this.formgroup.controls['projectCategory'];
                this.projectSector = this.formgroup.controls['projectSector'];
                this.data.financialYear = '';
                this.data.projectCategory = '';
                this.data.projectSector = '';   
                alert("first");
                this.getYearMaster();      
                this.getCategory();     
                this.getSectorType();
  }
  public ngOnInit() {
    //alert("inside ngOnInit");
    //this.yearMaster$.subscribe(yearMaster => this.yearMaster = yearMaster);
    this.networkserviceprovider.refresh$.subscribe(() => this.refresh());
  }  
  
  refresh() {
        alert("inside refresh");
        
        this.getYearMaster();      
        this.getCategory();     
        this.getSectorType();
  } 
  getYearMaster() {
    /*let loader = this.loadingController.create({
      content: "Loading  Financial Year ... "
    });
    loader.present();*/
    if(this.global1.getnetwork())
    {
    this.projectplanprovider.getYearMaster()
    .then(data => {
      this.year = data;
      alert("yeardata:"+JSON.stringify(data));
      this.yearMasterSub$.next(data);
      //loader.dismiss();
    });
  } else {
    //loader.dismiss();
    this.presentAlert();
  }

}
  getCategory() 
  {
    /*let loader = this.loadingController.create({
      content: "Loading  Project Category ... "
    });  
    loader.present();*/
    if(this.global1.getnetwork())
    {
      this.connectivityFlag = true;
      this.projectplanprovider.getCategory()
      .then(data => {
        //this.searchFlag = true;
        this.category = data;
        alert("categorydata:"+JSON.stringify(data));
        this.categorySub$.next(data);
        //loader.dismiss();
      });
    } else {
      //loader.dismiss();
      this.presentAlert();
    } 
  }

  getSectorType() 
  {
    /*let loader = this.loadingController.create({
      content: "Loading  Project Sector ... "
    });  
    loader.present();*/
    if(this.global1.getnetwork())
    {
      this.connectivityFlag = true;
      this.projectplanprovider.getSectorType()
      .then(data => {
        //this.searchFlag = true;
        this.sector = data;
        alert("sectordata:"+JSON.stringify(data));
        this.sectorTypeSub$.next(data);
       //loader.dismiss();
      });
    } else {
     // loader.dismiss();
      this.presentAlert();
    } 
    /*if(loader) {
      loader.dismiss();
    }*/
    //loader.present().then(() => { loader.dismiss(); });
  } 

  getProjectList(financialyear,projectcategory,projectsector,lbid) 
  {
    //alert(lbid);
    //alert("fy:"+financialyear);
    let loader = this.loadingController.create({
      content: "Loading  Project(s) ... "
    });  
    loader.present();
    if(this.global1.getnetwork())
    {
      this.connectivityFlag = true;
      this.selectedItem = false;
      this.projectplanprovider.selectApprovalDetails(lbid,projectcategory,projectsector,financialyear)
      .then(data => {
        this.searchFlag = true;
        this.result = data;
        //alert("searchresul: "+JSON.stringify(data));
        loader.dismiss();
      });
    } else {
      loader.dismiss();
      this.presentAlert();
    } 


  }


  selectProjectDetails(lbid,yearid,projectno) 
  {
    let loader = this.loadingController.create({
      content: "Loading project details ... "
    });  
    loader.present();
    if(this.global1.getnetwork())
    {
      this.selectedItem = true;
      this.connectivityFlag = true;
      this.projectplanprovider.selectProjectDetails(lbid,yearid,projectno)
      .then(data => {
        this.searchFlag = true;
        this.result = data;
        this.resultdesc = data;
        loader.dismiss();
      });
    } else {
      loader.dismiss();
      this.presentAlert();
    }
  }
  
  presentAlert() 
  {
      let alert = this.alertCtrl.create({
        title: 'No Network',
        subTitle: 'You are offline, please be online to search project plan(s)',
        buttons: ['OK']
      });
      alert.present();
  }

  async ionViewDidEnter() {
    await this.fetchLBSettings();  
    await this.getLBSettings();
    if(this.global1.getnetwork())
    {
      this.getYearMaster();
      //alert(this.year);
      this.connectivityFlag = true;

    } else {
      this.presentAlert();
    }  

  }

  async fetchLBSettings() 
  {
    let lbid = await this.storage.get('lbid');
    let lbname = await this.storage.get('lbname');
    let distid = await this.storage.get('distid');
    let lbtype = await this.storage.get('lbtype');
    if(lbid) { 
      //set the value already ...
    } else {
      //Default value if not set before
      this.storage.set('lbid', 290);
      this.storage.set('lbname', 'Amboori Grama Panchayat');
      this.storage.set('distid', 1);
      this.storage.set('lbtype', 5);
    }
  }

  async getLBSettings()
  {
    this.lbid = await this.storage.get('lbid');
    this.lbname = await this.storage.get('lbname');
    this.distid = await this.storage.get('distid');
    this.lbtype = await this.storage.get('lbtype');
  }



  ionViewDidLoad() {
    console.log('ionViewDidLoad ProjectplanPage');
  }

}


Waiting your Fast reply

Thanks

Anes

@anespa Well, you have to update something in the template to make it change. What you should update when getYearMaster() returns? Is the field year? Then you should do something like:

this.yearMaster$.subscribe(yearMaster => {
	console.log('yearMaster', yearMaster, this.year);			
	this.year = yearMaster
});

What do you want to update when getCategory() returns? Is the field category?

this.category$.subscribe(category=> {
	console.log('category', category, this.category);			
	this.category = category
});

And so on. Put some logs so that you know what happens. Just adapt it to your use case.

As a side note, it seems your page is too polluted. It needs some refactoring.

Dear Lucas,
I tried as like below , nothing happends

import { Component, OnInit } from '@angular/core';
import { NavController, NavParams, AlertController, LoadingController } from 'ionic-angular';
import { ProjectplanProvider } from "../../providers/projectplan/projectplan";
import { NetworkServiceProvider } from "../../providers/network-service/network-service";
import {GlobalProvider} from "../../providers/global/global";
import { FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms';
import { Storage } from '@ionic/storage';
import { Subject } from 'rxjs/Subject';
// For network
//import { Network } from '@ionic-native/network';

/**
 * Generated class for the ProjectplanPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@Component({
  selector: 'page-projectplan',
  templateUrl: 'projectplan.html',
})
export class ProjectplanPage implements OnInit {
  formgroup:FormGroup;
  financialYear:AbstractControl;
  projectCategory:AbstractControl;
  projectSector:AbstractControl; 
  private yearMasterSub$ = new Subject<any>();
  private categorySub$ = new Subject<any>();    
  private sectorTypeSub$ = new Subject<any>();    
  private yearMaster$ = this.yearMasterSub$.asObservable();
  private category$ = this.categorySub$.asObservable();
  private sectorType$ = this.sectorTypeSub$.asObservable();
  data:any = {};
  result: any;
  resultdesc: any;
  searchFlag: boolean = false;
  connectivityFlag: boolean = false;
  selectedItem: boolean = false;
  year: any;
  public category: any=0;
  public sector: any=0;
  public lbid: number;
  public lbname: string;
  public distid: number;
  public lbtype: number;
  constructor(public navCtrl: NavController, public navParams: NavParams, 
              public projectplanprovider: ProjectplanProvider,
              public networkserviceprovider: NetworkServiceProvider,
              public formbuilder: FormBuilder,
              private alertCtrl: AlertController,
              public loadingController: LoadingController,
              public global1:GlobalProvider,
              private storage: Storage
              ) {
                this.formgroup = formbuilder.group({
                  financialYear:['',Validators.required],
                  projectCategory:['',Validators.required],
                  projectSector:['',Validators.required],
                });
                this.financialYear = this.formgroup.controls['financialYear'];
                this.projectCategory = this.formgroup.controls['projectCategory'];
                this.projectSector = this.formgroup.controls['projectSector'];
                this.data.financialYear = '';
                this.data.projectCategory = '';
                this.data.projectSector = '';   
                alert("first");
                this.getYearMaster();      
                this.getCategory();     
                this.getSectorType();
  }
  public ngOnInit() {
    //alert("inside ngOnInit");
    //this.yearMaster$.subscribe(yearMaster => this.yearMaster = yearMaster);
    this.networkserviceprovider.refresh$.subscribe(() => this.refresh());

  }  
  
  refresh() {
        alert("inside refresh");
        this.yearMaster$.subscribe(yearMaster => {
          console.log('yearMaster', yearMaster, this.year);			
          this.year = yearMaster
        });
        this.category$.subscribe(category=> {
          console.log('category', category, this.category);			
          this.category = category
        });
        this.sectorType$.subscribe(sector=> {
          console.log('sector', sector, this.sector);			
          this.sector = sector
        });
        
        
        
       // this.getYearMaster();      
       // this.getCategory();     
       // this.getSectorType();
  } 
  getYearMaster() {
    /*let loader = this.loadingController.create({
      content: "Loading  Financial Year ... "
    });
    loader.present();*/
    if(this.global1.getnetwork())
    {
    this.projectplanprovider.getYearMaster()
    .then(data => {
      this.year = data;
      alert("yeardata:"+JSON.stringify(data));
      this.yearMasterSub$.next(data);
      //loader.dismiss();
    });
  } else {
    //loader.dismiss();
    this.presentAlert();
  }

}
  getCategory() 
  {
    /*let loader = this.loadingController.create({
      content: "Loading  Project Category ... "
    });  
    loader.present();*/
    if(this.global1.getnetwork())
    {
      this.connectivityFlag = true;
      this.projectplanprovider.getCategory()
      .then(data => {
        //this.searchFlag = true;
        this.category = data;
        alert("categorydata:"+JSON.stringify(data));
        this.categorySub$.next(data);
        //loader.dismiss();
      });
    } else {
      //loader.dismiss();
      this.presentAlert();
    } 
  }

  getSectorType() 
  {
    /*let loader = this.loadingController.create({
      content: "Loading  Project Sector ... "
    });  
    loader.present();*/
    if(this.global1.getnetwork())
    {
      this.connectivityFlag = true;
      this.projectplanprovider.getSectorType()
      .then(data => {
        //this.searchFlag = true;
        this.sector = data;
        alert("sectordata:"+JSON.stringify(data));
        this.sectorTypeSub$.next(data);
       //loader.dismiss();
      });
    } else {
     // loader.dismiss();
      this.presentAlert();
    } 
    /*if(loader) {
      loader.dismiss();
    }*/
    //loader.present().then(() => { loader.dismiss(); });
  } 

  getProjectList(financialyear,projectcategory,projectsector,lbid) 
  {
    //alert(lbid);
    //alert("fy:"+financialyear);
    let loader = this.loadingController.create({
      content: "Loading  Project(s) ... "
    });  
    loader.present();
    if(this.global1.getnetwork())
    {
      this.connectivityFlag = true;
      this.selectedItem = false;
      this.projectplanprovider.selectApprovalDetails(lbid,projectcategory,projectsector,financialyear)
      .then(data => {
        this.searchFlag = true;
        this.result = data;
        //alert("searchresul: "+JSON.stringify(data));
        loader.dismiss();
      });
    } else {
      loader.dismiss();
      this.presentAlert();
    } 


  }


  selectProjectDetails(lbid,yearid,projectno) 
  {
    let loader = this.loadingController.create({
      content: "Loading project details ... "
    });  
    loader.present();
    if(this.global1.getnetwork())
    {
      this.selectedItem = true;
      this.connectivityFlag = true;
      this.projectplanprovider.selectProjectDetails(lbid,yearid,projectno)
      .then(data => {
        this.searchFlag = true;
        this.result = data;
        this.resultdesc = data;
        loader.dismiss();
      });
    } else {
      loader.dismiss();
      this.presentAlert();
    }
  }
  
  presentAlert() 
  {
      let alert = this.alertCtrl.create({
        title: 'No Network',
        subTitle: 'You are offline, please be online to search project plan(s)',
        buttons: ['OK']
      });
      alert.present();
  }

  async ionViewDidEnter() {
    await this.fetchLBSettings();  
    await this.getLBSettings();
    if(this.global1.getnetwork())
    {
      this.getYearMaster();
      //alert(this.year);
      this.connectivityFlag = true;

    } else {
      this.presentAlert();
    }  

  }

  async fetchLBSettings() 
  {
    let lbid = await this.storage.get('lbid');
    let lbname = await this.storage.get('lbname');
    let distid = await this.storage.get('distid');
    let lbtype = await this.storage.get('lbtype');
    if(lbid) { 
      //set the value already ...
    } else {
      //Default value if not set before
      this.storage.set('lbid', 290);
      this.storage.set('lbname', 'Amboori Grama Panchayat');
      this.storage.set('distid', 1);
      this.storage.set('lbtype', 5);
    }
  }

  async getLBSettings()
  {
    this.lbid = await this.storage.get('lbid');
    this.lbname = await this.storage.get('lbname');
    this.distid = await this.storage.get('distid');
    this.lbtype = await this.storage.get('lbtype');
  }



  ionViewDidLoad() {
    console.log('ionViewDidLoad ProjectplanPage');
  }

}

Please advise

Thanks

Anes

@anespa That should not be in the refresh() method, but in ngOnInit() (subscribe only once, then listen to the events).

The refresh should be like before, calling this.getYearMaster() etc…

First it’s better to understand what your code is doing, otherwise you will be lost.

In the case of YearMaster:

  1. You are listening to the event from the moment the component was created, calling this.yearMaster$.subscribe() in ngOnInit().
  2. The page should refresh, the refresh method is called, and it calls this.getYearMaster().
  3. this.getYearMaster() call a webservice (make a http call).
  4. When the http call returns successfully, it will emit an event (the event is emitted in this.yearMasterSub$.next(data)).
  5. Because you subscribed to the event (see [1]), you will receive it (yearMaster will be logged, then this.year = yearMaster, and if year is referenced in the template, the HTML will be changed).

The same is valid for the other cases (like category).

So, I advise to try to anderstand how your component is behaving, so that you don’t be lost when reading it.

After that, try to move getYearMaster(), getCategory() and getSectorType() to a service, as well as the subjects and observables in the top of your component, to make your component cleaner.

Dear Lucas,

I tried your code as below. But could not get populated the data on template.

import { Component, OnInit } from '@angular/core';
import { NavController, NavParams, AlertController, LoadingController } from 'ionic-angular';
import { ProjectplanProvider } from "../../providers/projectplan/projectplan";
import { NetworkServiceProvider } from "../../providers/network-service/network-service";
import {GlobalProvider} from "../../providers/global/global";
import { FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms';
import { Storage } from '@ionic/storage';
import { Subject } from 'rxjs/Subject';
// For network
//import { Network } from '@ionic-native/network';

/**
 * Generated class for the ProjectplanPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@Component({
  selector: 'page-projectplan',
  templateUrl: 'projectplan.html',
})
export class ProjectplanPage implements OnInit {
  formgroup:FormGroup;
  financialYear:AbstractControl;
  projectCategory:AbstractControl;
  projectSector:AbstractControl; 
  private yearMasterSub$ = new Subject<any>();
  private categorySub$ = new Subject<any>();    
  private sectorTypeSub$ = new Subject<any>();    
  private yearMaster$ = this.yearMasterSub$.asObservable();
  private category$ = this.categorySub$.asObservable();
  private sectorType$ = this.sectorTypeSub$.asObservable();
  data:any = {};
  result: any;
  resultdesc: any;
  searchFlag: boolean = false;
  connectivityFlag: boolean = false;
  selectedItem: boolean = false;
  year: any;
  public category: any=0;
  public sector: any=0;
  public lbid: number;
  public lbname: string;
  public distid: number;
  public lbtype: number;
  constructor(public navCtrl: NavController, public navParams: NavParams, 
              public projectplanprovider: ProjectplanProvider,
              public networkserviceprovider: NetworkServiceProvider,
              public formbuilder: FormBuilder,
              private alertCtrl: AlertController,
              public loadingController: LoadingController,
              public global1:GlobalProvider,
              private storage: Storage
              ) {
                this.formgroup = formbuilder.group({
                  financialYear:['',Validators.required],
                  projectCategory:['',Validators.required],
                  projectSector:['',Validators.required],
                });
                this.financialYear = this.formgroup.controls['financialYear'];
                this.projectCategory = this.formgroup.controls['projectCategory'];
                this.projectSector = this.formgroup.controls['projectSector'];
                this.data.financialYear = '';
                this.data.projectCategory = '';
                this.data.projectSector = '';   
                alert("first");
                this.getYearMaster();      
                this.getCategory();     
                this.getSectorType();
  }
  public ngOnInit() {
    //alert("inside ngOnInit");
    //this.yearMaster$.subscribe(yearMaster => this.yearMaster = yearMaster);

    this.networkserviceprovider.refresh$.subscribe(() => this.refresh());
    this.yearMaster$.subscribe(yearMaster => {
      console.log('yearMaster', yearMaster, this.year);			
      this.year = yearMaster
    });
    this.category$.subscribe(category=> {
      console.log('category', category, this.category);			
      this.category = category
    });
    this.sectorType$.subscribe(sectorType=> {
      console.log('sectorType', sectorType, this.sector);			
      this.sector = sectorType
    });

  }  
  
  refresh() {
        alert("inside refresh");
        this.getYearMaster();      
        this.getCategory();     
        this.getSectorType();
  } 
  getYearMaster() {
    /*let loader = this.loadingController.create({
      content: "Loading  Financial Year ... "
    });
    loader.present();*/
    if(this.global1.getnetwork())
    {
    this.projectplanprovider.getYearMaster()
    .then(data => {
      this.year = data;
      alert("yeardata:"+JSON.stringify(data));
      this.yearMasterSub$.next(data);
      //loader.dismiss();
    });
  } else {
    //loader.dismiss();
    this.presentAlert();
  }

}
  getCategory() 
  {
    /*let loader = this.loadingController.create({
      content: "Loading  Project Category ... "
    });  
    loader.present();*/
    if(this.global1.getnetwork())
    {
      this.connectivityFlag = true;
      this.projectplanprovider.getCategory()
      .then(data => {
        //this.searchFlag = true;
        this.category = data;
        alert("categorydata:"+JSON.stringify(data));
        this.categorySub$.next(data);
        //loader.dismiss();
      });
    } else {
      //loader.dismiss();
      this.presentAlert();
    } 
  }

  getSectorType() 
  {
    /*let loader = this.loadingController.create({
      content: "Loading  Project Sector ... "
    });  
    loader.present();*/
    if(this.global1.getnetwork())
    {
      this.connectivityFlag = true;
      this.projectplanprovider.getSectorType()
      .then(data => {
        //this.searchFlag = true;
        this.sector = data;
        alert("sectordata:"+JSON.stringify(data));
        this.sectorTypeSub$.next(data);
       //loader.dismiss();
      });
    } else {
     // loader.dismiss();
      this.presentAlert();
    } 
    /*if(loader) {
      loader.dismiss();
    }*/
    //loader.present().then(() => { loader.dismiss(); });
  } 

  getProjectList(financialyear,projectcategory,projectsector,lbid) 
  {
    //alert(lbid);
    //alert("fy:"+financialyear);
    let loader = this.loadingController.create({
      content: "Loading  Project(s) ... "
    });  
    loader.present();
    if(this.global1.getnetwork())
    {
      this.connectivityFlag = true;
      this.selectedItem = false;
      this.projectplanprovider.selectApprovalDetails(lbid,projectcategory,projectsector,financialyear)
      .then(data => {
        this.searchFlag = true;
        this.result = data;
        //alert("searchresul: "+JSON.stringify(data));
        loader.dismiss();
      });
    } else {
      loader.dismiss();
      this.presentAlert();
    } 


  }


  selectProjectDetails(lbid,yearid,projectno) 
  {
    let loader = this.loadingController.create({
      content: "Loading project details ... "
    });  
    loader.present();
    if(this.global1.getnetwork())
    {
      this.selectedItem = true;
      this.connectivityFlag = true;
      this.projectplanprovider.selectProjectDetails(lbid,yearid,projectno)
      .then(data => {
        this.searchFlag = true;
        this.result = data;
        this.resultdesc = data;
        loader.dismiss();
      });
    } else {
      loader.dismiss();
      this.presentAlert();
    }
  }
  
  presentAlert() 
  {
      let alert = this.alertCtrl.create({
        title: 'No Network',
        subTitle: 'You are offline, please be online to search project plan(s)',
        buttons: ['OK']
      });
      alert.present();
  }

  async ionViewDidEnter() {
    await this.fetchLBSettings();  
    await this.getLBSettings();
    if(this.global1.getnetwork())
    {
      this.getYearMaster();
      //alert(this.year);
      this.connectivityFlag = true;

    } else {
      this.presentAlert();
    }  

  }

  async fetchLBSettings() 
  {
    let lbid = await this.storage.get('lbid');
    let lbname = await this.storage.get('lbname');
    let distid = await this.storage.get('distid');
    let lbtype = await this.storage.get('lbtype');
    if(lbid) { 
      //set the value already ...
    } else {
      //Default value if not set before
      this.storage.set('lbid', 290);
      this.storage.set('lbname', 'Amboori Grama Panchayat');
      this.storage.set('distid', 1);
      this.storage.set('lbtype', 5);
    }
  }

  async getLBSettings()
  {
    this.lbid = await this.storage.get('lbid');
    this.lbname = await this.storage.get('lbname');
    this.distid = await this.storage.get('distid');
    this.lbtype = await this.storage.get('lbtype');
  }



  ionViewDidLoad() {
    console.log('ionViewDidLoad ProjectplanPage');
  }

}

Thanks

Anes P A

@anespa I can’t help you much in that.

  1. What are the logs?
  2. When the network change the refresh is called? (you se the alert inside refresh?)
  3. You get the alert alert("yeardata:"+JSON.stringify(data))?
  4. You see the log console.log('yearMaster', yearMaster, this.year).

If you see all that, put a <div>Year: {{ year | json }}</div> in the template (html) and see if it shows the correct data.

Dear Lucas,

  1. That Refresh alert works fine

  2. Yes

  3. No that value not came…

please advise

Thanks

Anes

@anespa I see that you call this.getYearMaster(); in a lot of places. Especially, you have the following:

this.getYearMaster();      
this.getCategory();     
this.getSectorType();

in your constructor. If this returns before ngOnInit() is called (probably not, but possible), then you would call the subject before subscribing.

  1. Remove it from the constructor and call this.refresh() in the end of ngOnInit().
  2. Change your subjects creation to new ReplaySubject<any>(1) (instead of new Subject<any>(), to have the last value, if the subscription happens after the next() is called).
  3. See if it works and the browser shows (in the console) the log yearMaster.
  4. If it doesn’t work, try to put inside the ngOnInit(), as the last call in it, this.yearMasterSub$.next('test');, and see if it logs in the browser yearMaster with the value test.

It’s not working got TS error on ReplaySubject when I follow steps 1 to 3.

You need to import it from rxjs, of course.

I tried it like ,

import { Subject } from ‘rxjs/Subject’;

but show TS Error…
Do you please answer this post : How to call a function in app.component.ts menu before going a component to check connection exist?

it’s an alternative for my problem.

Thanks

Anes

@anespa, to use ReplaySubject you have to import ReplaySubject, not Subject:

import { ReplaySubject } from 'rxjs/ReplaySubject',