Issue
I’m new in Angular and Observables. My problem is:
in my component HomePage I call service that call http.get and return an observable. On my template HomePage I use async for this data$. I need to call another void function in ngOnInit that will use data$ when it is returned. So I can not to figured it out how to do this.
HomePage.ts
data$: Observable<any>;
ngOnInit(): void {
this.data$ = this.dataService.getMyData(); //I need userId that will be returned here
this.sendMessage(data.userId);//how to call this function after data$ is returned?
}
sendMessage(data.userId){
//send this userId
}
}
HomePage.html
<app-homepage form="true" *ngIf="{ data: data$ | async} as myData">
<div *ngIf="data.userId">
///....
I’ve tried this: but each time I input some data on the page – it calls sendMessage() multiple times…
this.data$ = this.dataService.getMyData().pipe(
tap((data) => {
this.sendMessage(data.userId);
console.log("in pipe")//here I see multiple calls when I click on checkbox for exemple..
}));
Solution
Try
this.data$ = this.dataService.getMyData().pipe(
take(1),
tap((data) => {
this.sendMessage(data.userId);
console.log("in pipe")//here I see multiple calls when I click on checkbox for exemple..
}
));