Angular's website provides methods for data interaction between parent and child components, such as Viewchild, Eventemitter
But if you want to synchronize data between siblings, you don't seem to be giving too much information.
Sometimes we think that after you modify the data in one component, it is immediately reflected in another component, or you may need to invoke a method from another component, we can use the RXJS.
The following source code in Https://github.com/eleven26/angular-observer
1. First, we define a service that is used to interact with the data within the application
Import {injectable} from ' @angular/core ', @Injectable () export class Storeservice {public storageobj = {}; Set (key, value) { This.storageobj[key] = value; } Get (key) { return this.storageobj[key]; } Remove (key) { delete This.storageobj[key] }}
2. We add the following code to the component that needs to listen for data changes, which is written directly in the AppComponent
Import {Component, OnInit} from ' @angular/core '; import {storeservice} from './store.service '; import {Observable} from ' Rxjs/observable '; @Component ({ selector: ' App-root ', templateurl: './app.component.html ', styleurls: [ './app.component.css ']}) Export class AppComponent implements oninit{ title = ' App works! '; Constructor (private Storeservice:storeservice) {} Ngoninit () {let myobserver:observable<any> = OBSERVABLE.CREATE (Observer) and { //payload to store data that requires interaction between different components let payload = This.storeService.get (' Payload '); if (payload) { //do something if (payload[' type '] = = ' Set-title ') { this.title = payload[' title ']; } this.storeService.remove (' payload '); } Observer.next (); }); Saved to a public service so that the same observer object can be used between different components This.storeService.set (' Myobserver ', myobserver);} }
In the above code, we define an observable object myobserver, and when we call subscribe on this method, the Observable.create callback is called.
Then we get the data that needs to be processed from the Storesrevice, the specific data format is freely stipulated,
After we have processed the data, we remove the relevant data from the Storesrevice.
At the same time, we need to save the myobserver to Storeservice so that the different components get the same observer.
3, define a component, used to produce payload, similar to producer-consumer
Import {Component, OnInit} from ' @angular/core '; import {storeservice} from './store.service '; import {Observable} from ' Rxjs/observable '; @Component ({ selector: ' a-component ', Template: '
When we entered the title of the component, we found that the title of AppComponent also changed accordingly.
In this way, our effect is realized.
Angular using RXJS to monitor sibling component data changes