Home > Software engineering >  Result of API call is only retaining in my angular 7 subscribe method and Getting undefined outside
Result of API call is only retaining in my angular 7 subscribe method and Getting undefined outside

Time:04-25

I am trying to call back end API from my angular front end and getting data while testing using POSTMAN API client application. When I am trying to console log inside my subscription function, its getting in console. But when I am trying to print after function clause, its giving undefined.

My function call is like the following from component.ts file,

this.surveyroomService
.getWeightedAverageByRoomAllocationIdApiMethod(this.row.nRoomAllocationId)
  .subscribe
     (data=>{this.getWeightedAverageData=data;console.log(this.getWeightedAverageData); });

 
  console.log(this.getWeightedAverageData);

And my service layer is like the following,

 getWeightedAverageByRoomAllocationIdApiMethod(param:any) 
{
    return this.http
      .get(  this.baseurlService.getUrl()
             this.portNumberService.getSurveySurveyRoomPortNumber()
             this.instituteidentifierService.getInstitute()
             '/survey/surveyform/surveyroom/getWeightedAverageByRoomAllocationId?nRoomAllocationId=' param,
            {
              headers: this.applicationconfigService.getHeader()
            }
      );
}

How can I solve this problem of undefined here in my front end ? Can anyone please suggest or guide to correct my mistake here please

CodePudding user response:

The reason why console.log displays undefined is because it gets executed before the subscription is resolved (meaning: before you get data, or before your this.getWeightedAverageData=data). Even though you log it after you subscribe to the observable, you still don't have data at that point.

Since you don't have any data when you log it, you will have to wait until a response is returned. This means you can only interact with this.getWeightedAverageData in your callback. (Or at a later stage, on a button click if it happens after data is received etc)

CodePudding user response:

the console log is executed before the http get method return an answer. You can move the console log inside the subscribe. If the api that you are calling return a single value, I suggest you to use a Promise with the async/await.

this.getWeightedAverageData = await this.surveyroomService.getWeightedAverageByRoomAllocationIdApiMethod(this.row.nRoomAllocationId).toPromise();
console.log(this.getWeightedAverageData);

In this way your code will be more readable and you will be sure that the console log will display the correct result from the api.

  • Related