Search code examples
arraysangularangular2-services

angular 2 share array through service


hello guys I am trying to share an array in Angular 2 trough a service from component 1 to component 2 but instead I get nothing here is my code

My Service

private employeeIdList = new Subject<any>();    
employeeIdList$ = this.employeeIdList.asObservable();

public setEmployeeList(employeeIdList){
    this.employeeIdList.next(employeeIdList);
}

From component 1 I am trying to do this:

this.sharedService.setEmployeeList(this.employeeId);

this.employeId is an array of elements

and when I try to access it like this

this.sharedService.employeeIdList$.subscribe(employeeList => {
  console.log(employeeList);
})

I get nothing, can you help me out to figure this out

thank you guys


Solution

  • I assume it's a timing issue that the event gets emitted before the receiver was able to subscribe. To work around use BehaviorSubject or ReplaySubject

    private employeeIdList = new BehaviorSubject<any>();    
    

    Another possible cause is that you provided the service at more than one place which might cause you to get more than one instance where one is emitting the event but the receiver is subscribing to another instance.