[英]Is there any way to make component as singleton in angular 2+?
我需要將組件作為一個單一的噸,所以我可以在應用程序中的任何地方使用它而無需再次初始化它。
怎么辦?
您需要使用靜態字段創建它,在構造函數中為其分配第一個實例,如果已經分配則拋出(有人試圖實例化第二個副本)。 然后您可以訪問靜態字段以在任何地方訪問實例。 大致是這樣的:
export class MyClass {
constructor() {
if (MyClass.instance) {
throw('Already instantiated');
}
MyClass.instance = this;
}
static instance: MyClass;
}
然后在任何其他組件/服務中,您可以訪問MyClass.instance
。
這聽起來像一個駭人聽聞的想法。 使組件成為單例的唯一原因是數據不會丟失,並且有多種方法可以在不使組件成為單例的情況下保留數據。 例如,將數據存儲在單例服務中,然后每次初始化組件時,從單例服務中獲取數據。 或者使用諸如 ngrx 之類的存儲解決方案。
使用新的:
@Injectable({
providedIn: 'root'
})
語法,服務自動變為單例並按需加載,無需將其添加到 providers 數組中。 這使得使用單例服務變得非常容易。
在組件中編寫以下代碼,您需要使其成為單例。 這里共享服務在根級別初始化,因此它在整個應用程序中都有一個實例。
constructor(public sharedService: SharedService) {
if (!this.sharedService.myComponent) {
this.sharedService.myComponent = this;
} else {
Object.assign(this, this.sharedService.myComponent);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.