POV
POV

Reputation: 12005

How to inject service in method?

I have a custom class:

class Global {
 public isMobileDevice() {
 }
}

So, I want to inject service class inside this method like:

public isMobileDevice(private deviceService: DeviceDetectorService): boolean {
    return true;
}

Because I Can not inject this service in constructor like this:

constructor(private deviceService: DeviceDetectorService) {
}

I tried this:

public isMobileDevice(): boolean {
    return new DeviceDetectorService();
 }

Upvotes: 2

Views: 1256

Answers (2)

Thatkookooguy
Thatkookooguy

Reputation: 7002

You can avoid injecting the service in your components' constructor by using static functions on a class that you plan to import where you want to use it instead of an angular service.

export class Global {
 public static isMobileDevice() {
 }
}

then, you use it like so:

import { Global } from '<path_to_global>';

class SomeComponent {
  isMobile = Global.isMobileDevice();
}

Upvotes: 3

Mark Verkiel
Mark Verkiel

Reputation: 1239

If you want to inject the service without constructor you could create a static method in your module class like this.

export class GlobalModule {

    static injector: Injector;
    constructor(injector: Injector) {
        GlobalModule.injector = injector;
    }
}

With the injector class you can get DeviceDetectorService

public isMobileDevice(): boolean {
    var deviceDetectorService = GlobalModule.injector.get(DeviceDetectorService);
    // Logic 
}

Make sure that the injector property is set in an early stage of your application.

Upvotes: 3

Related Questions