0

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

Derlin
  • 9,572
  • 2
  • 32
  • 53
Olga Matosova
  • 136
  • 1
  • 1
  • 10
  • there is no easy way to just watch changes to a variable, you have to somehow trigger a change event (via event emitter) or use an observable wrapper. here is a simple event emitter example: https://stackoverflow.com/questions/35869406/angular2-detect-change-in-service – Ahmed Musallam Sep 21 '17 at 16:00
  • Looks like you just set a new value to `planList` variable. It can't be "listened", second component should be notified when `planList` value changes, like with `ngOnChanges`. But if there were more components that should be notified if value changes, so best to convert `planList` into Observable – Julius Dzidzevičius Sep 21 '17 at 16:01

1 Answers1

1

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
});
Eeks33
  • 2,245
  • 1
  • 14
  • 17