How to keep your data in sync throughout your application?

拈花ヽ惹草 提交于 2019-12-24 21:34:31

问题


I have many components displaying single or multiple products provided by a service.

getProducts() {
    return this.http.get('/api/products');
}

getProduct(id) {
    return this.http.get('/api/product/'+id);
}

In some components, I can add new products or edit them using this service.

saveProduct(product) {
    if(product._id) {
        return this.http.put('/api/product/'+product._id, product);
    }

    return this.http.post('/api/product', product);
}

These components are displayed simultaneously but not directly connected to each other. So, whenever a change occurs, I need to notify all other components about this change.

I think observables are the way to go, but I'm not sure how to get started.

What is the right way to keep data maintained throughout my app?


回答1:


What you are looking for is a store. The most famous one is Redux which is used in nearly every React application. Angular has its own alternative, based on Redux and called ngrx store.




回答2:


If your objective is to multicast the data use RXJS's Subject or BehaviorSubject Subject acts as a bridge/proxy between the source Observable and many observers, making it possible for multiple observers to share the same Observable execution.

Advantages of BehaviorSubject over Subject

  1. It will always return the current value on subscription - there is no need to call onnext().
  2. It has a getValue() function to extract the last value as raw data.
  3. It ensures that the component always receives the most recent data.
  4. you can get an observable from behavior subject using the asobservable() method on BehaviorSubject.
  5. Subject vs BehaviorSubject

Service

private firstResponse=new BehaviorSubject<any>('');
 private secondResponse=new BehaviorSubject<any>('');
      CurrentDatafirst = this.firstResponse.asObservable();
      CurrentDatasecond = this.secondResponse.asObservable();

   getProducts() {
    return this.http.get('/api/products').
      subscribe(result=>this.firstResponse.next(result));//push data into observable
}

getProduct(id) {
    return this.http.get('/api/product/'+id).
           subscribe(result=>this.secondResponse.next(result));//push data into observable
}

Component1:

ngOnInit()
{
  this.CurrentDatafirst.subscribe(//value=>your logic);
  this.CurrentDatasecond.subscribe(//value=>your logic)

}

Component2:

 ngOnInit()
    {
      this.CurrentDatafirst.subscribe(//value=>your logic);
      this.CurrentDatasecond.subscribe(//value=>your logic)

    }


来源:https://stackoverflow.com/questions/51005288/how-to-keep-your-data-in-sync-throughout-your-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!