Refactoring repeatable code

Dear All,

I have this specific code that I have to include in each component before transitioning to each page. Basically I need to check whether the JWT has expired or not.

let isTokenExp = this.jwtHelper.isTokenExpired(data);
        if (isTokenExp) {
          let alert = this.alertCtrl.create({
            title: 'Warning',
            subTitle: 'Your session has been expired. You will be logged out.',
            buttons: ['Ok']
          })
          alert.present();
          alert.onDidDismiss(() => {
            //clear token
            this.authTokenService.deleteToken().then(() => {
              this.navCtrl.setRoot('LoginPage');
            }).catch((err) => {
              //alert error to user.
              this.navCtrl.setRoot('LoginPage');
            })
          })
        }

Would want a way to write it once and use it everywhere? Please advise.

Thanks,
Ashley

add your code into providers and whenever you want to use just import providers/yourfile.ts and make object in constructor to use their property and function

That I know. But injecting an alert controller in a provider would work? SetRoot in a provider would work?

yes it will definitely work. it is simple oops concept nothing else .

i have one SharedService.ts file in which i have all common function used all over the app such as toast,messagebox,loader,etc.
whenever i want to display loader or toast or something iwill just make an object of SharedService in constructor as below:

private sharedService: SharedService

and used it as :

this.sharedService.ShowMessage("Login Successful");

this.sharedService.ShowLoader();

it works perfect :+1::+1::+1: