I'm quite fresh in Angular, but somehow I like it! I enjoy the web components experience. It was refreshing. However, I faced a crazy challenge with little documentation of how to transfer data between 2 Siblings. The obvious answer is: But you can use a service! Right?
It sounds simple, but I couldn't find any proper documentation. I read a lot of stuff about this and nothing. All examples were too complicated. This pic represents what I was facing:
I needed to transfer the info from the SearchBox to the NavBar. And from the NavBar to the Map to locate the new point. Does it sound easy? Not exactly and I'd like to help you do it simpler. What do you need?
Install:
https://rxjs-dev.firebaseapp.com/
npm install rxjs
This library is the one that is going to do the trick to transfer it. I'm going to focus on the Siblings part since the other one (child to parent) is easier and well documented between @Outputs and @Inputs.
First, let's create a service for transferring the data between Siblings:
ng generate service message-transfer-service
Later inside of the class, we are going to define a BehaviorSubject that we are going to use to store "the transferable object".
export class Locations {
id: number;
lat: number;
lng: number;
name: string;
}
export class MessageTransferService {
private locations = new Locations();
//This is the key the Subject to transfer
locations$ = new BehaviorSubject<Locations>(this.locations)
setLocations(location: Locations) {
this.locations$.next(location);
}
constructor() { }
}
After you finish your service, you go to your AppModule and define your service in the providers:
providers: [MessageTransferService],
Later, in your Parent component. You set as a parameter of your constructor, your service.
constructor(private service: MessageTransferService){ }
//this function is an example for updating the value from the service
setLocations(currentLocation) {
let d : Location = JSON.parse(currentLocation);
this.service.setLocations(d);
}
Finally, you define the same constructor and the Subject in your Sibling class:
locations$: this.service.locations$;
constructor(private service: MessageTransferService) { }
ngOnInit() {
//this one is optional
this.service.locations$.subscribe(value =>
{
console.log(value);
// do something
});
}
And there you go, now you can transfer data between Siblings using a service in Angular!
And if you want to check it in action or see the source code. Here you have it!
https://fanmixco.github.io/gravitynow-angular
Top comments (0)