[英]Open same angular component as different instances at the same time
我有一個 angular 組件,它有一個數據源列表,該組件是從服務的 BehaviourSubject 訂閱的。
在 list.component.html 模板文件中:
<ng-container *ngFor="let item of items;">
<h2>item.name</h2>
</ng-container>
在 list.component.ts 文件中:
ngOnInit(): void {
this.service.items$.subscribe(data=>{
this.items = data;
});
}
單擊列表中的項目時,它會在同一個表中加載所選項目的子項目。
現在,我在這個組件旁邊有一個按鈕,它將打開一個 MatDialog window。
這個 MatDialog windows 應該包含上述相同的組件。
我試過的:
我為這個組件創建了一個包裝器,並在 MatDialog 中打開了包裝器。
wrapper.component.html
<div>
<app-list></app-list>
</div>
里面 list.component.html 在 MatDialog 中打開 WrapperComponent:
this.matDialog.open(WrapperComponent);
一切正常,直到我單擊 matDialog 中的列表項。
所選項目在 matDialog 的列表中加載。 但同時在后台原始 ListComponent 也在加載相同的值。 因為,當單擊列表中的項目時,來自 BehaviourSubject 的訂閱值會更新。
this.service.updateListValue = updatedValue;
原始 ListComponent 加載了路由器模塊和解析器。
我怎樣才能避免這種情況? 如何打開相同的組件但作為兩個不同的實例?
你能做到這一點,
為您服務 class @Injectable
替換: @Injectable({ providedIn: 'root' })
與: @Injectable({ providedIn: 'any' })
使用providedIn: 'root'
選項時,angular 注入器將使您的服務 class 充當 singleton 的整個應用程序實例。
當providedIn: 'any'
選項被使用時,Angular 注入器將為每個注入此服務的模塊實例化一個新服務。
獎勵:如果 Class ServiceA 僅由 ModuleA 使用,您可以使用
@Injectable({ providedIn: ModuleA })
。 當您擁有僅由單個模塊使用的服務時,這將是最佳選擇
為了擁有特定於組件的服務,您需要在@Component
裝飾器元數據中提供它。 這將為每個組件實例創建一個服務實例。
@Component({
providers: [SomeService],
})
您的服務也不應該在 root 中providedIn
。
@Injectable()
如果您想使用相同的組件和不同的元數據,您可以基於模塊有 2 種不同的服務實現。
您可以聲明一個代表服務的令牌
export const SERVICE_TOKEN: InjectionToken<SomeService> = new InjectionToken<SomeService>('Some Service Token');
然后在每個模塊中指定要注入的服務:
providers: [
{
provide: SERVICE_TOKEN,
useClass: SomeServiceA,
},
然后在組件的構造函數中像這樣注入它:
constructor(@Inject(SERVICE_TOKEN) private readonly someService: SomeService){}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.