I want to trigger load data ( which also load on init ) when user close dialog.
in AddUser-component.ts i have any logic and only important part
public onClose: Subject<any> = new Subject<any>();
this.addService.addNewUser(user).subscribe(res => {
this.onClose.next(res.body)
this.bsModalRef.hide();
}
and when trigger this in main component AllUser-components.ts i have
public addNewUser() {
this.bsModalRef = this.modalService.show(AddUserComponent);
(this.bsModalRef.content as AddUserComponent).onClose.subscribe(singleUserFromChildComponent)=>{
this.loadUser(); // HERE IS PROBLEM... when i console.log this.allUsers i don't see new added user .....
if (bill) {
this.lastAddedItem(this.allUsers, singleUserFromChildComponent);
}
this.bsModalRef.hide()
})
}
and above i have loadUser
private loadUser() {
this.service.getAllUsers(
).subscribe((res) => {
this.allUsers = res.body!;
})
}
this.allUsers var is not updated....not load new user.... why ? I load data and allUsers need to be updated with new data
this.allUsers = res.body!;
but not... i don't know why ?
Well its because the loadUser() method is asynchronous, and while you are loading it on modal close, it does not finish yet (also having nested subscriptions is a kind of bad practice, you can read more in that thread Why nested subscription is not good?)
What I can suggest you is to remove the subscribe invocation from loadUser method and return just an observable:
private loadUser() {
return this.service.getAllUsers().pipe(map((res: any) => res.body!),tap((res: any) => this.allUsers = res));
}
In your OnInit (or constructor method initialize allUsers in this way.
this.loadUser().pipe(first()).subscribe();
and then refactor your modal close part with the switchMap( it will wait untill your service.getAllUsers finished)
public addNewUser() {
this.bsModalRef = this.modalService.show(AddUserComponent);
(this.bsModalRef.content as AddUserComponent).onClose
.pipe(tap(singleUserFromChildComponent => this.singleUserFromChildComponent = singleUserFromChildComponent), switchMap(addedUser => (this.loadUser()))).subscribe(_ => {
if (bill) {
this.lastAddedItem(this.allUsers, this.singleUserFromChildComponent);
}
this.bsModalRef.hide()
});
}
also please add the lastAddedUser property to your component
public singleUserFromChildComponent: any;