问题
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
- It will always return the current value on subscription - there is no need to call
onnext().
- It has a
getValue()
function to extract the last value as raw data. - It ensures that the component always receives the most recent data.
- you can get an observable from behavior subject using the
asobservable()
method onBehaviorSubject
. - 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