Home > OS >  Async await not returning/showing any data from API
Async await not returning/showing any data from API

Time:12-08

I have an Ionic 6 Angular 14 app where for now I am trying to output data I get from an API...

I have created a service where I am getting the data from API and then I call the service in the component... The app compiles with no errors and there are no errors in the console in the browser...

Could someone help me figure out where I messed up?

Here is the code of my service:

async getCategories() {

 const token = await Preferences.get({ key: 'TOKEN_KEY' });

 const headers = new HttpHeaders().set('Authorization', `Bearer ${token.value}`);
 this.httpClient.get(`${environment.apiUrl}categories`, {headers}).subscribe(
 data => {
 this.categories = data;
    },
 error => {
 console.log('Error', error);
    }
  );
}

and here is the code from from the component.ts file:

ngOnInit() {
 this.getCategories();
}

getCategories() {
 this.categories = this.categoriesService.getCategories();
}

CodePudding user response:

You need to subscribe to observable in the component, not in the service. The service should only return the observable. Also any async function returns a Promise which you should either await, or use .then()

Service:

async getCategories() {
 const token = await Preferences.get({ key: 'TOKEN_KEY' });

 const headers = new HttpHeaders().set('Authorization', `Bearer ${token.value}`);
 return this.httpClient.get(`${environment.apiUrl}categories`, {headers});
}

Component:

ngOnInit() {
 this.getCategories();
}

getCategories() {
 this.categoriesService.getCategories().then(categoriesObservable => 
    categoriesObservable.subscribe(data => {
      this.categories = data;
    },
    error => {
      console.log('Error', error);
    }
  );
}

CodePudding user response:

a lot of problems can occur when mixing Promise and Observable - I recommended use only Observables as long as you can, but in your case you replace it with.

 async getCategories() {
 const token = await Preferences.get({ key: 'TOKEN_KEY' });

 const headers = new HttpHeaders().set('Authorization', `Bearer 
 ${token.value}`);
 try { 
   const categories = await lastValueFrom(this.httpClient.get(`${environment.apiUrl}categories`, {headers}));
   return categories;
   catch(err) {
     // log error
 }
}
}

this method will return Promise with the data

CodePudding user response:

You are setting something to the value returned from .getCategories() but this will not return any value.

CodePudding user response:

You need to review the tour of heros, seems you have a gap in your knowledge: https://angular.io/tutorial

  • Related