0

Overview:

I have a UI that allows a user to select one or more employees based on various search criteria. When they select them, I need to store the selected employees in an array, within my shared service.

Before any of this data is sent to the server, the array could be modified by adding more employees or removing some that exist in the array.

I need to be able to create and subscribe to an array of data in this shared service.

My Approach:

My initial approach was to use a BehaviorSubject so that I could call next and pass the data along when needed. This became an issue though because I didn't have a way to see all of the stored/selected users, only the last one that was passed through the BehaviorSubject.

Psuedo Code:

shared.service.ts

public selectedUsers = [];  //<- How do I store stuff in here?

private selectedUsersSub = new BehaviorSubject<any>(null);
selectedUsers$ = this.selectedUsersSub.asObservable();

setSelectedUsers(data) {
  this.selectedUsersSub.next(data);
}

get selectedUsers(){
  return this.selectedUsers;
}

component.ts:

this._reqService.selectedUsers$.subscribe(
      data => {
        if (data) {
          console.log('Observable Stream', data)
        }
      } 
    )

My goal here is to be able to store my selected employees in this selectedUsers array. My other components need to be able to subscribe so that they are always up-to-date with the current value of selectedUsers.

I also need to be able to access the current array of selected users at any time, not just the last value.

SBB
  • 7,079
  • 27
  • 82
  • 181
  • Possible duplicate of [Best way to share an array between two components using a service in Angular2?](https://stackoverflow.com/questions/42726109/best-way-to-share-an-array-between-two-components-using-a-service-in-angular2) – Adrien Brunelat Nov 27 '17 at 17:03

2 Answers2

0

Delete public selectedUsers = [];

delete get selectedUsers(){ return this.selectedUsers; }

And in any component you want to fetch the selectedUsers just subscribe to the public observable selectedUsers$

in a component this.subscription = this.yourService.selectedUser$.subscribe((users)=>//do stuff here like push theusersto the users array of the component)

The service needs to be inject to a shared module in order all the components to get the same state (data).

More details: https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

DrNio
  • 1,806
  • 1
  • 14
  • 22
0

Your approach is wrong here. You have 2 basic options in a shared service pattern. 1 is to use a store pattern where you have a predefined set of data manipulations and use the scan operator, this is more complex, the simpler is to pass the entire list every time you want to update the list.

So your components will not only send the update, they'll first get the entire list and then manipulate and then send it.

bryan60
  • 22,247
  • 3
  • 31
  • 47