2

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();
 }
9
  • 5
    Because I Can not inject this service in constructor like this why???? Commented May 21, 2019 at 13:49
  • 1
    So far as i know, angular only supports constructor injection. Commented May 21, 2019 at 13:50
  • Because there are a lot of places where I use instance Global, and I dont want pass instance DeviceDetectorService in each places. Commented May 21, 2019 at 13:51
  • Is this your first time creating a service in Angular? Are you asking how DI works? Commented May 21, 2019 at 13:52
  • No, it is another case, my file Global is already as service, But I want to use DeviceDetectorService as static or as Facade Commented May 21, 2019 at 13:54

2 Answers 2

3

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();
}
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.