Hey there! I'm currently facing a challenge where I need to pass an object from the 1st Component to the 2nd Component upon a click event. My approach involves using a data service with set and get functions:
Data Service
@Injectable({
providedIn: 'root'
})
export class DataService{
private subject = new Subject<any>();
setObject(obj) {
this.subject.next(obj)
}
getObject(): Observable <any> {
return this.subject;
}
}
In the 1st Component, I call the setObject(obj) method on a click event.
Parent Component HTML
<tbody>
<tr *ngFor="let item of tableElements;" (click)="onSelect(item)">
...
1st Component
export class ParentComponent {
constructor(private dataService: DataService) { }
onClick(obj: object) {
this.dataService.setObject(obj);
}
}
Now, in the 2nd Component, I am unsure about how to correctly subscribe to the Observable and display the object without just saving it to another variable directly. I have come across suggestions that discourage manipulating the observable that way.
2nd Component
export class ChildComponent {
displayedObject$: Observable<any>;
constructor(private dataService: DataService) {
this.displayedObject$ = dataService.getObject().pipe(
map((res) => {
console.log('value from data service' + res);
return res;
})
);
}
}
So, how can I properly showcase the object and its properties in my HTML template? I have already attempted:
Child Component HTML
<div> Value from Data Service = {{ displayedObject$ | async }} </div>
Although the console displays the object, unfortunately, it doesn't reflect in the template. Any insights on what could be going wrong?