Home > Software engineering >  Why do I receive data not on 1st click but on 2nd click in Angular?
Why do I receive data not on 1st click but on 2nd click in Angular?

Time:04-30

There are multiple modules (for example career, departments, and many more) in which I receive data from SQL server through stored procedure (Select query), into the backend which is NEST JS and then into Angular frontend to display those modules (career, departments, etc.) but the problem is that when I click the button then nothing happens, and when I click the button 2nd time then the data displays on webpage. The backend is working fine as I checked in Postman, the data is received the first time. The problem is with the frontend.

Angular Service.ts code:

getdepartments(){
    const headers = new HttpHeaders().set('Content-Type', 'application/json').set('Authorization','Bearer' ' ' GlobalService.authtoken);
  
    return this.http.post<any>('http://localhost:3000/employee/getdepartments/',null,{headers}).subscribe(({data}) => {
      this.dataout = data});
  
  }

Component.ts code:

departments(){
   this.departmentsService.getdepartments();
   this.dataout=this.departmentsService.dataout;
    }

HTML code:

<div>
    <tr>
        <th>Departments </th>
        <th>Description </th>
    </tr>
    <tr *ngFor="let index of dataout">
        <td>{{index.Department}}</td>
        <td>{{index.Description}}</td>
    </tr>
</div>

Webpage:

enter image description here

CodePudding user response:

The problem is that the asynchronous call to your backend has not finished when you set the data for your component:

departments(){
  // this starts the call to your backend
  this.departmentsService.getdepartments(); 

  /* you immediately set "dataout" to datatout of your service, 
     but at this point your backend call has not finished so dataout 
     in your service is not set yet
 */
  this.dataout=this.departmentsService.dataout; 
}

You could solve this for example by exposing the observable from your http.post call to your backend to your component (btw this should be a get call for obvious reasons):

getdepartments(){
  const headers = new HttpHeaders().set('Content-Type', 'application/json').set('Authorization','Bearer' ' ' GlobalService.authtoken);
  return this.http.post<any>('http://localhost:3000/employee/getdepartments/',null,{headers});
}

And in your component subscribe to that observable:

departments(){
  this.departmentsService.getdepartments().subscribe( data => this.dataout = data);
}
  • Related