[英]How to inject dependency in to a class in Angular 8
我想在我的 class 的 static class 中使用 ngx translate。 我怎樣才能做到這一點? 如何在 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;
}
}
只需使用Singleton 服務。 Angular 已經涵蓋了您,因為 Singleton 在內部由 DI 容器管理。 該實例只會被創建一次,在另一個組件中注入MyService
將等同於您的MyService.getInstance()
。
您只需將providedIn
scope 設置為"root"
即可:
@Injectable({
providedIn: 'root',
})
export class MyService {
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.