简体   繁体   中英

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. 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.
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.

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. Can you help me? Thanks

You could store the agent instance in an Observable and than subscribe in the component to that 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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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