簡體   English   中英

如何使用Subjects以角度6分享全局數據

[英]How to use Subjects to share global data in angular 6

我一直在努力尋找最佳解決方案,以便在共享同一個父級的兩個組件之間共享一些數據。

我正在使用角材料步進器。 第1步有一個組件,第2步有另一個組件。 我想要做的是從步驟1“單擊”組件中的1按鈕,並刷新影響步驟2中的組件的數據數組。

這是我的代碼:

全球服務:

  export class GlobalDataService {
  private reserveSource = new BehaviorSubject<any[]>([]);

  currentReserve = this.reserveSource.asObservable();

  constructor() { }

  changeReserve(reserve: any[]) {
    this.reserveSource.next(reserve)

  }
}

試圖更新的組件1:

setSpace(id) {
this.apiObservableService
  .getService('http://localhost:8080/Spaces/' + id)
  .subscribe(
    result => {
      this.space = result;
      this.globaldataservice.changeReserve(result.reserves);
      sessionStorage.setItem('currentSpace', JSON.stringify(result));
    },
    error => console.log(error)
  );

}

嘗試讀取和刷新的組件2:

ngOnInit(): void {

    this.currentUser = JSON.parse(sessionStorage.getItem('currentUser'));
    this.currentSpace = JSON.parse(sessionStorage.getItem('currentSpace'));

    this.globaldataservice.currentReserve.subscribe(message => this.reserves = message)
    console.log(this.reserves);
  }

坦率地說,你的代碼應該可以正常工作,但這是我如何處理它,以防我錯過你的代碼中的東西。

GlobalDataStore還應該將BehaviourSubject作為Observable提供,因此您可以訂閱它。

還要將Behavioursubject私有化。

export class GlobalDataService {
  private reserveSource = new BehaviorSubject<any[]>([]);

  get reserveSource() {
       return this.reserveSource.asObservable();
  }
}

然后只需在組件中訂閱它。

作為獎勵,我還在我的商店中實現了這些功能(因為我也在使用BehaviourSubject)

//Gets the last value, that was pushed to the BehaviourSubject
get reserveSourceLastValue() {
   return this.reserveSource.getValue();
}

//Deep clones the last value, if I want a precise copy for form editing buffer
get reserveSourceForEdit() {
    return __lodash.cloneDeep( this.reserveSource.getValue() );
}

專業表演提示!

作為最后一點,如果您不取消訂閱可觀察對象,那么即使在組件本身被銷毀之后,它們也會永遠保持打開狀態。 更糟糕的是,由於您在ngOnInit中初始化了observable,因此每次您在此組件之間路由時,都會創建一個新訂閱。

請閱讀本文,了解如何優雅地取消訂閱組件中的訂閱。

Angular / RxJs什么時候應該取消訂閱“訂閱”

暫無
暫無

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

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