简体   繁体   中英

How to inject dependency in to a class in Angular 8

I want to use ngx translate inside a static class in my class. How can I do this? How to do dependency injection in a singleton class?

import { Injectable } from "@angular/core";
@Injectable()
export class MyService {
    static instance: MyService;

    static getInstance() {
        if (MyService.instance) {
            return MyService.instance;
        }

        MyService.instance = new MyService();
        return MyService.instance;
    }

    constructor() {
        if (!MyService.instance) {
             MyService.instance = this;
        }

        return MyService.instance;
    }
}

Just use Singleton services . Angular has already got you covered, since Singleton are managed internally by the DI Container. The instance will be created only one time, and injecting MyService in another component will be equivalent to your MyService.getInstance() .

You just need to set providedIn scope for your service to "root" :

@Injectable({
  providedIn: 'root',
})
export class MyService {
   // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM