Reputation: 799
I'm trying to use an observable to communicate an array of strings from one component to another. I'm able to create the observable in the one component and attach to it from the other, but I am drawing a complete blank on how I change the value of the observable so the 2nd component can pick up the changes. I create the array of strings via a dialog, and that is working fine. Everytime I close the dialog, I have the new array of strings, but I haven't been able to figure out how to update the observable array so the new values will get passed to the subscriber component. Here is where I declare the observable:
public getIMEIs(): any {
console.log('GetIMEIs');
const IMEIsObservable = new Observable( observer => {
console.log('returning devices: ', this.devicesToTrack);
observer.next(this.devicesToTrack);
});
return IMEIsObservable;
}
And here is where I subscribe to it in the 2nd component:
const devicesToTrackObservable = this.devicesToTrackService.getIMEIs();
devicesToTrackObservable.subscribe((devices: string[]) => {
this.devicesToTrack = devices;
console.log('devices to track: ', devices);
})
And here is where the dialog exit is processed:
dialogRef.afterClosed().subscribe(result => {
console.log('after dialog, returnData:', result);
this.devicesToTrack = result[0];
console.log('IMEIs to track:',this.devicesToTrack);
});
When I have a new array of strings to send to the 2nd component, how do I set the new value of the observable? I've tried creating a set function, but nothing I try passes the compiler as far as referencing the observable. Is it something simple or do I need to rethink the way I'm doing things?
Thanks.....
Upvotes: 1
Views: 46
Reputation: 1778
Sample code to segregate the observable into a service and use it to communicate between the two components:
DevicesToTrackService {
IMEIsObservable$ = new Subject<any>();
getIMEIs() {
return this.IMEIsObservable$.asObservable();
}
publishIMEIs(data: any) {
this.IMEIsObservable$.next(data);
}
}
componentOne {
...
const devicesToTrackObservable = this.devicesToTrackService.getIMEIs();
devicesToTrackObservable.subscribe((devices: string[]) => {
this.devicesToTrack = devices;
console.log('devices to track: ', devices);
})
}
componentTwo {
...
dialogRef.afterClosed().subscribe(result => {
console.log('after dialog, returnData:', result);
this.devicesToTrack = result[0];
this.devicesToTrackService.publishIMEIs(this.devicesToTrack)
console.log('IMEIs to track:',this.devicesToTrack);
});
}
Upvotes: 1