简体   繁体   中英

Angular2/4 - Creating an array of data to share across multiple components via service

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.

Delete public selectedUsers = [];

delete get selectedUsers(){ return this.selectedUsers; } 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 the users to 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

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.

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