Reputation: 103
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;
}
}
Upvotes: 1
Views: 121
Reputation: 3501
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 {
// ...
}
Upvotes: 1