简体   繁体   English

如何使用Subjects以角度6分享全局数据

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

I have been trying to find the best solution to share some data beetween two componentes that share the same parent. 我一直在努力寻找最佳解决方案,以便在共享同一个父级的两个组件之间共享一些数据。

I am using an angular-material stepper. 我正在使用角材料步进器。 Step 1 has one component and step 2 has another one. 第1步有一个组件,第2步有另一个组件。 What i am trying to do is to "click" 1 button in the component from the step 1 and refresh an array of data that affects component in step 2. 我想要做的是从步骤1“单击”组件中的1按钮,并刷新影响步骤2中的组件的数据数组。

This is my code: 这是我的代码:

Global service: 全球服务:

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

  currentReserve = this.reserveSource.asObservable();

  constructor() { }

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

  }
}

Component 1 that tries to update: 试图更新的组件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)
  );

} }

Component 2 that tries to read and refresh: 尝试读取和刷新的组件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);
  }

Quite frankly, your code should work fine, but here is how I deal with it, in case I missed something in your code. 坦率地说,你的代码应该可以正常工作,但这是我如何处理它,以防我错过你的代码中的东西。

GlobalDataStore should also give out the BehaviourSubject as Observable, so you can subscribe to it. GlobalDataStore还应该将BehaviourSubject作为Observable提供,因此您可以订阅它。

Also make behavioursubject private. 还要将Behavioursubject私有化。

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

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

Then just subscribe to it in the component. 然后只需在组件中订阅它。

As a bonus, I also implement these functions in my stores (since I am also using BehaviourSubject) 作为奖励,我还在我的商店中实现了这些功能(因为我也在使用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() );
}

PRO PERFORMANCE TIP! 专业表演提示!

As a last note, if you do not unsubscribe from observables, then they are left open forever, even after the component itself is destroyed. 作为最后一点,如果您不取消订阅可观察对象,那么即使在组件本身被销毁之后,它们也会永远保持打开状态。 To make matters worse, since you have the observable initialized in ngOnInit, then every time you route to and from this component, a new subscription is created. 更糟糕的是,由于您在ngOnInit中初始化了observable,因此每次您在此组件之间路由时,都会创建一个新订阅。

Please read this article on how to gracefully unsubscribe from subscriptions in components. 请阅读本文,了解如何优雅地取消订阅组件中的订阅。

Angular/RxJs When should I unsubscribe from `Subscription` Angular / RxJs什么时候应该取消订阅“订阅”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM