Angular Uncaught (in promise) error when getting data with service

Issue

I need some help in my first Ionic – Angular app… I’m trying to display a list of categories and I keep getting this error in browser console… Altho app compiles with no errors..
Console log error is: Uncaught (in promise): Error: NG02200: Cannot find a differ supporting object '[object Promise]' of type 'object'. NgFor only supports binding to Iterables, such as Arrays.

So the structure of my application is that I have a categories.service.ts where I am getting the categories like so:

export class CategoriesService {
  categories: any = [];

  constructor(
    private authService: AuthenticationService,
    private httpClient: HttpClient,
  ) { }

  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);
      }
    );
  }
}

then in my categories.page.ts my code is:

  categories: any = [];

  constructor(
    private categoriesService: CategoriesService
  ) {}

  ngOnInit() {
    this.getCategories();
  }

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

And in the html I am trying to display them like so:

<ion-col size="6" *ngFor="let category of categories">
  <div id="{{category.seo_url}}" class="card">
    <div class="card-overlay"></div>
    <div class="card-cat-title">
      <h4><a routerLink="/category/{{category.seo_url}}">{{ category.name }}</a></h4>
    </div>
  </div>
</ion-col>

What have I done wrong? please help 🙂

Solution

categoriesService.getCategories() is not returning an array, is returning a Promise, which is an asynchronous action.

You have two options: await the response or resolve the Promise:

a) resolve the promise:

this.categoriesService.getCategories()
.then( cats => {
    this.categories = cats;
});

b) await the promise:

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

But notice that in this case you have to add the async keyword to the function.

Answered By – Oscar Sales DEV

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published