I'm not sure what I'm doing wrong here but my variable is not getting changed inside subscribe(). Below is my code snippet where I'm calling getAllCompanies() from save(). The expectation is that I would be able to assign the updated cmps value(the server returns the correct updated value) to companyList but it doesn't happen unfortunately. As a result, the rendered view has wrong data because the companyList object is not updated:
export class MyComponent implements OnInit {
companyList: CompanyMaster[] = []
// lines of code
// ......
// ......
getAllCompanies() {
this.loaderService.show();
this.companyService.getAllCompanies().subscribe(cmps =>
{
this.companyList = cmps;
},
error => {
this.toastr.error(error),
this.loaderService.hide()
},
() => this.loaderService.hide()
);
}
save(formData: NgForm){
// lines of code
// ......
this.companyService.SaveCompanyDetails(company)
.subscribe(data => {
// lines of code
// ......
this.getAllCompanies()
// lines of code
// ..
});
}
// lines of code
// ......
}
I also tried using ngZone like it is suggested here but it doesn't seem to work either:
this.companyService.getAllCompanies().subscribe(cmps =>
{
this.ngZone.run( () => {
this.companyList = cmps;
});
},
error => {
this.toastr.error(error),
this.loaderService.hide()
},
() => this.loaderService.hide()
);
}
Any help would be highly appreciated, thank you.