简体   繁体   中英

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

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

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