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}}" >
<div ></div>
<div >
<h4><a routerLink="/category/{{category.seo_url}}">{{ category.name }}</a></h4>
</div>
</div>
</ion-col>
What have I done wrong? please help :)
CodePudding user response:
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.
CodePudding user response:
You have a gap in your Angular knowledge. Review the tour of heros https://angular.io/tutorial.