My App has a Header section and body section, I am using routes so that the body section can navigate between pages, while the header is always there.
The data for the header comes from two services productService.getProducts()
and priceService.getPrices()
which is able to be modified on two of the pages productService.addProduct(produceID)
, productService.removeProduct(productID)
.
The data in the services is updating correctly, but I need a way to tell the header to call getProducts()
and getPrices()
again.
I thought I could have a callback from the pages, but it seems you cannot include a callback in a route?
You can define a Subject
in your service and subscribe to it in your header's component. Every time you update data in service, just call Subject.next()
.
subject: Subject<string> = new Subject();
updateData() {
// your own logic
this.subject.next();
}
Then you can do what you want(such as call some other functions) at Subject.subscribe()
.
product$ = this.service.subject; // Subject defined at your service
constructor() {
this.product$.subscribe(() => {
console.log('product data has been updated!');
});
}
Also, If you just want to get the newest data, you can just transform updated data via subject.next(newestData)
, and then you can get what you want at subject.subscribe()
.
refer this simple Plunker demo .
I think in order to solve your problem more efficiently you need to consider of using ngrx this way you can subscribe for a store in your header and then on related action gets fired you can run do stuff
in your header.
It might be looking something like
Dispatch an action that mutate the store
this.store.dispatch(new yourthing.SomeAction());
Subscribe for a change: this.store.select(fromYourThing.getYourThing) .subscribe((thing) => { // do stuff }); });
this.store.select(fromYourThing.getYourThing) .subscribe((thing) => { // do stuff }); });
For more details on ngrx
check these links:
https://blog.angular.io/announcing-ngrx-4-87df0eaa2806
https://blog.nrwl.io/ngrx-patterns-and-techniques-f46126e2b1e5
https://blog.nrwl.io/using-ngrx-4-to-manage-state-in-angular-applications-64e7a1f84b7b
Also run this example-app locally so you can see how it all goes in action.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.