Accessing a Service inside a static method


#1

Team,

I ran into an issue today working on my private mobile project. My challenge is pretty straightforward but I cannot seem to find a solution for it. Here it goes:

I am using Dependency Injection to inject a service into my models in an ionic2 application and have a need to access one of those services in a static method. I have done this several times in Java using spring framework, with spring, all we need to do is to get the application context and get the service from it.

Is there a way to get that working in ionic and typescript? I am new to javascript and angular world but I believe there should be something similar. Please forgive my indulgence and any help would definitely be appreciated.

Thanks!


#2

Please explain why the method must be static.


#3

Um… Static methods with dependencies? :thinking: Are you sure?
You can provide you service in app.js and in static method get instance.

let service: YourService = YourService.getInstance();

Maybe it works :slight_smile:


#4

how will that work when there is no static getInstance method implemented on the service?


#5

I followed this example Asynchronous form validation but tried to remove static from all those methods but that too did not work. It seems as if there is some kind of phase issues with form validation and services in model class.


#6

Very strange code…

You must implement it like static ) I found for you example, but you no need injector, just the instance implementation.


#7

Ok I am not sure how to implement the instance as you describe above. Here is what I think you mean

static getInstance(){
return this; // or return a reference to this class
}


#8

OK, I would try creating the validator as a lexically scoped closure variable instead of having it be a method. Something like this:

let validator = (control) => {
  return this.injectedThingy.doSomething(control); 
};

this.nameControl = new Control('', , validator);

Another option would be to refactor your validator into its own class, which can use DI in its constructor:

@Injectable()
class AsyncValidator {
  constructor(private _svc:SomeService) {
  }

  validate(control:Control):Promise<ValidationResult> {
    return this._svc.doSomething(control);
  }
}

@Injectable()
class FormHavingPage {
  constructor(fb: FormBuilder) {
    fb.group({
      'name': ['', , AsyncValidator]
    });
  }
}

You can use a class name for a validator instead of a function as long as DI can instantiate it and it has a method named validate. Untested code, sorry for syntax errors.


Ionic2 Form server validation