Ionic 使用服务获取数据时出现Angular 未捕获(承诺中)错误

p1tboqfb  于 2022-12-08  发布在  Ionic
关注(0)|答案(2)|浏览(245)

我需要一些帮助,在我的第一个离子-Angular 的应用程序...我试图显示类别列表,我一直得到这个错误在浏览器控制台.. Altho应用程序编译没有错误..控制台日志错误是: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.
因此,我的应用程序的结构是,我有一个categories.service.ts,在其中我可以获得如下所示的类别:

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

那么在我的categories.page.ts中我的代码是:

categories: any = [];

  constructor(
    private categoriesService: CategoriesService
  ) {}

  ngOnInit() {
    this.getCategories();
  }

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

在html中,我尝试这样显示它们:

<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>

我做错了什么?请帮助:)

holgip5t

holgip5t1#

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.

5vf7fwbs

5vf7fwbs2#

您的Angular 知识有差距。请检阅英雄https://angular.io/tutorial之旅。

相关问题