0

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.

The Inquisitive Coder
  • 1,085
  • 3
  • 20
  • 43
  • Your code seems to be fine, you could check the console for any other exceptions. Unless you are using on push changes, the UI should be updated. see this quick example: https://angular-cimdos.stackblitz.io – Caio Oliveira Aug 01 '22 at 15:51

1 Answers1

0

Your code is fine. Can you please add your companyService code here?