Angular2:NgFor 仅支持绑定到 Iterables,例如 Arrays
Angular2: NgFor only supports binding to Iterables such as Arrays
我正在为一个大学项目创建一个 Web 应用程序,它分为两部分:一个 Web API 和一个连接到所述 API 的前端。我正在制作的网络应用程序是一个食谱网站。由于没有接触过 Angular 等新技术,我在他们的网站上学习了英雄之旅教程,并且处理得相当好。
但是,我现在必须 link 不使用模拟数据源,而是使用我的 API 从中提取数据。
我有几个组件,所以我包含了教程 HTTP 部分的相关文件,recipe.service.ts 和 recipes.component.html,对于这部分应用程序(教程中应该编辑的唯一文件。
在我看来,Angular 并未通过错误代码将响应读取为数组,尽管假定的 return 文本为 JSON。我查过这个问题,但似乎无法得到正确使用我的代码的答案。
recipe.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { Recipe } from './recipe';
import { RECIPES } from './mock-recipes';
import { MessageService } from './message.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable()
export class RecipeService {
private recipesURL = 'http://localhost:3000/api/recipes';
constructor(
private http: HttpClient,
private messageService: MessageService) {}
getRecipes(): Observable<Recipe[]> {
//Todo: send the message after fetching heroes
//this.messageService.add('RecipeService: fetched recipes');
return this.http.get<Recipe[]>(this.recipesURL);
}
getRecipe(id: number): Observable<Recipe> {
this.messageService.add(`RecipeService: fetched recipe id=${id}`);
return of(RECIPES.find(recipe => recipe.recipeID === id));
//return of(RECIPES.find(recipe => recipe.recipeName));
}
private log(message: string) {
this.messageService.add('RecipeService: ' + message);
}
}
recipes.component.html
<h2>My Recipes</h2>
<ul class="recipes">
<li *ngFor="let recipe of recipes">
<a routerLink="/detail/{{recipe.recipeID}}">
<span class = "badge">{{recipe.recipeName}}</span> {{recipe.userID}}
</a>
</li>
</ul>
运行 Angular 应用程序时我在控制台中遇到的错误:
ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
at NgForOf.ngOnChanges (common.js:2537)
at checkAndUpdateDirectiveInline (core.js:12092)
at checkAndUpdateNodeInline (core.js:13598)
at checkAndUpdateNode (core.js:13541)
at debugCheckAndUpdateNode (core.js:14413)
at debugCheckDirectivesFn (core.js:14354)
at Object.eval [as updateDirectives] (RecipesComponent.html:3)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:14339)
at checkAndUpdateView (core.js:13508)
at callViewAction (core.js:13858)
应用程序应该撤回的片段(如 JSON):
{
"Error": false,
"Message": "Success",
"Recipes": [
{
"recipeID": 1,
"recipeName": "orci",
"ingredients": "Vivamus metus arcu, adipiscing molestie, hendrerit at, vulputate vitae, nisl. Aenean lectus. Pellentesque eget nunc. Donec quis orci eget orci vehicula condimentum. Curabitur in libero ut massa volutpat convallis.",
"method": "Vivamus in felis eu sapien cursus vestibulum. Proin eu mi. Nulla ac enim. In tempor, turpis nec euismod scelerisque, quam turpis adipiscing lorem, vitae mattis nibh ligula nec sem. Duis aliquam convallis nunc. Proin at turpis a pede posuere nonummy. Integer non velit.",
"createdBy": 150,
"postedTime": "2017-06-01 15:11:27"
},
{
"recipeID": 2,
"recipeName": "sit",
"ingredients": "Suspendisse potenti. In eleifend quam a odio.",
"method": "Donec semper sapien a libero. Nam dui. Proin leo odio, porttitor id, consequat in, consequat ut, nulla. Sed accumsan felis. Ut at dolor quis odio consequat varius. Integer ac leo.",
"createdBy": 982,
"postedTime": "2017-02-21 08:40:58"
}
]
}
如果有人能帮助我那就太好了。
谢谢:)
编辑 - 我的 recipes.component.ts
import { Component, OnInit } from '@angular/core';
import { Recipe } from '../recipe';
import { RecipeService } from '../recipe.service'
@Component({
selector: 'app-recipes',
templateUrl: './recipes.component.html',
styleUrls: ['./recipes.component.css']
})
export class RecipesComponent implements OnInit {
recipes: Recipe[];
constructor(private recipeService: RecipeService) { }
ngOnInit() {
this.getRecipes();
}
getRecipes(): void {
this.recipeService.getRecipes().subscribe(recipes => this.recipes = recipes);
}
}
getRecipes(): void {
this.recipeService.getRecipes().subscribe(recipes => this.recipes = recipes.Recipes);
}
因为你的响应是一个对象,而不是一个数组。您需要将 this.recipes
设置为 recipes.Recipes
。根据:
{
"Error": false,
"Message": "Success",
"Recipes": [... //here is your array
您 return 来自服务的整个 json 响应,而不仅仅是食谱数组。您不能使用 *ngFor 迭代对象。更改 this.recipes = 食谱 如下。
getRecipes(): void {
this.recipeService.getRecipes().subscribe(recipes =>
if(recipes){
this.recipes = recipes.Recipes;
}
);
}
我正在为一个大学项目创建一个 Web 应用程序,它分为两部分:一个 Web API 和一个连接到所述 API 的前端。我正在制作的网络应用程序是一个食谱网站。由于没有接触过 Angular 等新技术,我在他们的网站上学习了英雄之旅教程,并且处理得相当好。
但是,我现在必须 link 不使用模拟数据源,而是使用我的 API 从中提取数据。
我有几个组件,所以我包含了教程 HTTP 部分的相关文件,recipe.service.ts 和 recipes.component.html,对于这部分应用程序(教程中应该编辑的唯一文件。
在我看来,Angular 并未通过错误代码将响应读取为数组,尽管假定的 return 文本为 JSON。我查过这个问题,但似乎无法得到正确使用我的代码的答案。
recipe.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { Recipe } from './recipe';
import { RECIPES } from './mock-recipes';
import { MessageService } from './message.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable()
export class RecipeService {
private recipesURL = 'http://localhost:3000/api/recipes';
constructor(
private http: HttpClient,
private messageService: MessageService) {}
getRecipes(): Observable<Recipe[]> {
//Todo: send the message after fetching heroes
//this.messageService.add('RecipeService: fetched recipes');
return this.http.get<Recipe[]>(this.recipesURL);
}
getRecipe(id: number): Observable<Recipe> {
this.messageService.add(`RecipeService: fetched recipe id=${id}`);
return of(RECIPES.find(recipe => recipe.recipeID === id));
//return of(RECIPES.find(recipe => recipe.recipeName));
}
private log(message: string) {
this.messageService.add('RecipeService: ' + message);
}
}
recipes.component.html
<h2>My Recipes</h2>
<ul class="recipes">
<li *ngFor="let recipe of recipes">
<a routerLink="/detail/{{recipe.recipeID}}">
<span class = "badge">{{recipe.recipeName}}</span> {{recipe.userID}}
</a>
</li>
</ul>
运行 Angular 应用程序时我在控制台中遇到的错误:
ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
at NgForOf.ngOnChanges (common.js:2537)
at checkAndUpdateDirectiveInline (core.js:12092)
at checkAndUpdateNodeInline (core.js:13598)
at checkAndUpdateNode (core.js:13541)
at debugCheckAndUpdateNode (core.js:14413)
at debugCheckDirectivesFn (core.js:14354)
at Object.eval [as updateDirectives] (RecipesComponent.html:3)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:14339)
at checkAndUpdateView (core.js:13508)
at callViewAction (core.js:13858)
应用程序应该撤回的片段(如 JSON):
{
"Error": false,
"Message": "Success",
"Recipes": [
{
"recipeID": 1,
"recipeName": "orci",
"ingredients": "Vivamus metus arcu, adipiscing molestie, hendrerit at, vulputate vitae, nisl. Aenean lectus. Pellentesque eget nunc. Donec quis orci eget orci vehicula condimentum. Curabitur in libero ut massa volutpat convallis.",
"method": "Vivamus in felis eu sapien cursus vestibulum. Proin eu mi. Nulla ac enim. In tempor, turpis nec euismod scelerisque, quam turpis adipiscing lorem, vitae mattis nibh ligula nec sem. Duis aliquam convallis nunc. Proin at turpis a pede posuere nonummy. Integer non velit.",
"createdBy": 150,
"postedTime": "2017-06-01 15:11:27"
},
{
"recipeID": 2,
"recipeName": "sit",
"ingredients": "Suspendisse potenti. In eleifend quam a odio.",
"method": "Donec semper sapien a libero. Nam dui. Proin leo odio, porttitor id, consequat in, consequat ut, nulla. Sed accumsan felis. Ut at dolor quis odio consequat varius. Integer ac leo.",
"createdBy": 982,
"postedTime": "2017-02-21 08:40:58"
}
]
}
如果有人能帮助我那就太好了。
谢谢:)
编辑 - 我的 recipes.component.ts
import { Component, OnInit } from '@angular/core';
import { Recipe } from '../recipe';
import { RecipeService } from '../recipe.service'
@Component({
selector: 'app-recipes',
templateUrl: './recipes.component.html',
styleUrls: ['./recipes.component.css']
})
export class RecipesComponent implements OnInit {
recipes: Recipe[];
constructor(private recipeService: RecipeService) { }
ngOnInit() {
this.getRecipes();
}
getRecipes(): void {
this.recipeService.getRecipes().subscribe(recipes => this.recipes = recipes);
}
}
getRecipes(): void {
this.recipeService.getRecipes().subscribe(recipes => this.recipes = recipes.Recipes);
}
因为你的响应是一个对象,而不是一个数组。您需要将 this.recipes
设置为 recipes.Recipes
。根据:
{
"Error": false,
"Message": "Success",
"Recipes": [... //here is your array
您 return 来自服务的整个 json 响应,而不仅仅是食谱数组。您不能使用 *ngFor 迭代对象。更改 this.recipes = 食谱 如下。
getRecipes(): void {
this.recipeService.getRecipes().subscribe(recipes =>
if(recipes){
this.recipes = recipes.Recipes;
}
);
}