Search code examples
angularsocketsservicerxjsangular2-services

Listen to variable update in service Angular2/4


I have some object in global service. One of component uses socket and updates this object, but other component doesn't get any changes.

PlanService

@Injectable()
export class PlanService {

    private subject = new Subject<any>();
    private planSubject = new Subject<any>();
    public planList;
    constructor( private socket: SocketClientService) { 
           this.socket.on('plan');

    }

First Component update planList

constructor(
  private planService: PlanService,
    private socket: SocketClientService,
    public projectsService: ProjectsService,
    private groupsService: GroupsService,
    private calendarShare: CalendarDateShareService,

) {
    this.socket.on('plan');
    this.planService.getUserBusy().distinctUntilChanged().subscribe((data) => {
        planService.planList = data;  /* update */

    });

Second Component should listen and update

planService.planList

I am new in Angular 2


Solution

  • You can make your planList into a subject like your private members you have there.

    @Injectable()
    export class PlanService {
        ...
        public planList = new Subject<any>();
        ...
    }
    

    Then pass in a new value using next:

    ...
    this.planService.getUserBusy().distinctUntilChanged().subscribe((data) => 
    {
      this.planService.planList.next(data);  /* update */
    });
    ...
    

    Then you can subscribe to the planList changes in any other component/service

    ...
    
    this.planService.planList.subscribe(data => {
      console.log(data) // planList Data
    });