簡體   English   中英

Angular2 / 4-創建數據數組以通過服務在多個組件之間共享

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

概述:

我有一個UI,允許用戶根據各種搜索條件選擇一個或多個員工。 當他們選擇他們時,我需要將選擇的雇員存儲在我的共享服務中的一個陣列中。

在將這些數據中的任何一個發送到服務器之前,可以通過添加更多雇員或刪除陣列中存在的某些雇員來修改陣列。

我需要能夠在此共享服務中創建和訂閱數據數組。

我的方法:

我最初的方法是使用BehaviorSubject以便可以調用next並在需要時傳遞數據。 但是,這成為一個問題,因為我沒有辦法查看所有已存儲/選定的用戶,只有最后一個通過BehaviorSubject傳遞的用戶。

偽代碼:

共享服務

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

我的目標是能夠將我選擇的員工存儲在這個selectedUsers數組中。 我的其他組件需要能夠訂閱,以便它們始終與selectedUsers的當前值保持最新。

我還需要能夠隨時訪問選定用戶的當前數組,而不僅僅是最后一個值。

刪除public selectedUsers = [];

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

在您要獲取selectedUsers的任何組件中,只需訂閱公共可觀察的selectedUsers$

在組件中this.subscription = this.yourService.selectedUser$.subscribe((users)=>//do stuff here like push the用戶this.subscription = this.yourService.selectedUser$.subscribe((users)=>//do stuff here like push the to the users array of the component)

該服務需要注入到共享模塊中,以便所有組件都獲得相同的狀態(數據)。

更多詳細信息: https : //angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

您的方法在這里是錯誤的。 共享服務模式中有2個基本選項。 第一種是使用存儲模式,在該模式中您具有一組預定義的數據操作並使用掃描運算符,這更復雜,更簡單的方法是每次您要更新列表時都傳遞整個列表。

因此,您的組件不僅將發送更新,而且還將首先獲取整個列表,然后進行操作然后將其發送。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM