【发布时间】:2021-06-19 05:16:14
【问题描述】:
我正在尝试从 API 获取数据并将其显示在我的组件中。我可以成功获取数据,因为它在控制台中打印,但我无法在页面上显示它。
控制台给了我错误:错误:找不到类型为“object”的不同支持对象“[object Object]”。 NgFor 只支持绑定到数组等 Iterables。
我尝试过使用 JSON 占位符 API,它工作正常,所以我认为这与我正在使用的 API 中数据的结构方式有关。
这是我的组件:
import { Component, OnInit } from '@angular/core';
import { RecipeService } from '../services/recipe.service';
import { Recipe } from '../models/Recipe';
@Component({
selector: 'app-recipe',
templateUrl: './recipe.component.html',
styleUrls: ['./recipe.component.css']
})
export class RecipeComponent implements OnInit {
recipes: Recipe
constructor(
private recipeService: RecipeService) { }
ngOnInit() {
this.recipeService.getRecipes().subscribe(response => {
this.recipes = response;
console.log(response)
});
}
}
这是我的服务:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Recipe } from '../models/Recipe';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class RecipeService {
constructor(private httpClient:HttpClient) { }
apiUrl:string = 'https://www.themealdb.com/api/json/v1/1/categories.php';
getRecipes():Observable<Recipe> {
return this.httpClient.get<Recipe>(`${this.apiUrl}`)
}
}
这是我的 HTML 页面:
<div class="container mx-auto mt-20">
<h2 class="text-2xl">Welcome to the recipes page</h2>
<div class="grid grid-cols-6 mt-10 recipe-grid">
<div class="recipe" *ngFor="let recipe of recipes">
<h4>{{recipe.title}}</h4>
</div>
</div>
</div>
更新
我现在更改了响应,所以它在一个数组中,我想
this.recipes = 响应;改成 this.recipes = [response];
这消除了以前的错误,但现在说的是
“Recipe[]”类型中缺少属性“strCategory”,但“Recipe”类型中需要。
strCategory 是目前我在我的食谱模型中放入的唯一数据
export class Recipe {
strCategory: string;
}
我该如何解决这个问题?
【问题讨论】:
-
该错误告诉您,您正在尝试 *ngFor 对象而不是数组。首先,您可能会得到一个数组,所以我建议像这样
recipes: Recipe[] = [];进行初始化。那么,你能告诉我们console.log给你什么吗? -
@Emilien 那是我尝试的第一件事,输出是一样的。我在某处读到 API 不输出数组,而是输出对象,但我不确定。