[英]Angular 6 update a component from the service
我使用的是角度6,調用服務方法時需要更新組件。 我有一個變量agent
,可從html保留所選代理,因此可以從多個組件中獲取此變量,並且可以從特定按鈕中刪除該代理。
當我調用deleteAgent時,我必須更新接口,因此我需要一種“告訴”代理已刪除組件的方法。
export class ComponentService {
private agent : Agent
constructor() { }
/************ AGENT MANAGEMENT *****************/
get getAgent(){
return this.agent;
}
setAgent(agent: Agent){
this.agent = agent;
}
deleteAgent(){
this.agent = null;
//inform the component about the change
}
}
我讀了有關ReplaySubject的文章,但我不知道這是否是正確的方法以及如何刪除元素。 你能幫助我嗎? 謝謝
您可以將代理程序實例存儲在Observable中,然后在組件中訂閱該Observable。
export class ComponentService {
private _agent = Subject<Agent>();
constructor() { }
/************ AGENT MANAGEMENT *****************/
get agent(){
return this._agent.asObservable();
}
set agent(agent: Agent){
this._agent.next(agent);
}
deleteAgent(){
this.agent = null;
}
}
我用下面的代碼解決了,我不知道這是否是最好的代碼:
export class ComponentService {
private agent: Agent;
// Observable navItem source
agentChange = new ReplaySubject<Agent>(1);
constructor() { }
/************ AGENT MANAGEMENT *****************/
get getAgent(){
return this.agent;
}
setAgent(agent: Agent){
this.agent = agent;
}
deleteAgent(){
this.agentChange.next(this.agent);
this.agent = null;
}
}
然后在組件的客戶庫中,我有訂閱和取消訂閱的destroy方法:
this.componentService.agentChange.subscribe((agent:Agent)=>{
//on success instruction
})
ngOnDestroy() {
this.componentService.agentChange.unsubscribe();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.