Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting LoadingController in static method in angular 2

I have tried to inject LoadingController in static method, but it is not getting injected. Is it possible to inject LoadingController in static method?

I have tried below code:

import { LoadingController, Loading } from 'ionic-angular';
import { Inject } from '@angular/core'

export class Commons {

    @Inject(LoadingController)
    static showLoadingMask( loadingText: string ) {
        //Getting Null
        let loadCtrl: LoadingController;
    }
}

The other code that I have tried is:

import { LoadingController, Loading } from 'ionic-angular';
import { Inject } from '@angular/core'

export class Commons {
    static showLoadingMask( loadingText: string, @Inject(LoadingController) loadCtrl ) {
        //Getting Null
        if( loadCtrl ) {
            //Null
        } else {
            //Always executing else
        }
    }

}

I don't want to have constructor in this class, as I only want to provide static methods that are reusable across project for common task.

like image 273
Mohammad Ashfaq Avatar asked Mar 17 '26 11:03

Mohammad Ashfaq


1 Answers

I'm not sure if this is the best way to do it, but you can send a reference to the injector and use it to get the instances of the providers. For example

import { LoadingController, Loading } from 'ionic-angular';
import { Injector } from '@angular/core'

export class Commons {
    static showLoadingMask(injector: Injector, loadingText: string ) {
        let loadCtrl: LoadingController = this.injector.get(LoadingController);
    }
}

And in the component where you want to use it, it'd be like

import { Component, Injector } from '@angular/core';
// ...

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage {

    constructor(..., public injector: Injector) { ... }

    public yourMethod(): void {
      Commons.showLoadingMask(this.injector, 'Loading...');
    }    
}
like image 166
sebaferreras Avatar answered Mar 20 '26 06:03

sebaferreras