简体   繁体   English

Angular 6从服务中更新组件

[英]Angular 6 update a component from the service

I'm using angular 6 and I need to update the component when I call a service method. 我使用的是角度6,调用服务方法时需要更新组件。 I have a variable agent that keep the selected agent from html so I get this variable from several component and I can delete this agent from a specific button. 我有一个变量agent ,可从html保留所选代理,因此可以从多个组件中获取此变量,并且可以从特定按钮中删除该代理。
When I call deleteAgent I have to update the interface so I need a way to "tell" to the component that the agent was deleted. 当我调用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
   }
}

I read about ReplaySubject but I don't know if it is the correct way and how to remove element. 我读了有关ReplaySubject的文章,但我不知道这是否是正确的方法以及如何删除元素。 Can you help me? 你能帮助我吗? Thanks 谢谢

You could store the agent instance in an Observable and than subscribe in the component to that observable. 您可以将代理程序实例存储在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;
 }
}

I resolved with this code, I don't know if it is the best code: 我用下面的代码解决了,我不知道这是否是最好的代码:

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;
   }
}

then in the custroctor of component I have the subscribe and the unsubscribe into destroy method: 然后在组件的客户库中,我有订阅和取消订阅的destroy方法:

this.componentService.agentChange.subscribe((agent:Agent)=>{
     //on success instruction
    })

ngOnDestroy() {
    this.componentService.agentChange.unsubscribe();
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM