簡體   English   中英

Angular2:NgFor僅支持綁定到可迭代對象,例如數組

[英]Angular2: NgFor only supports binding to Iterables such as Arrays

我正在為一個大學項目創建一個Web應用程序,該應用程序分為兩個部分:Web API和連接到該API的Frontend。 我正在制作的Web應用程序是一個食譜網站。 由於沒有接觸過諸如Angular之類的新技術,我進入了其網站上的“英雄巡回賽”教程,並對此進行了很好的應對。

但是,現在我必須鏈接,不要使用模擬數據源,而要使用我的API從中提取數據。

我有幾個組件,因此在本應用程序的這一部分中,本教程的HTTP部分包括了相應的文件recipe.service.tsrecipes.component.html (唯一的文件應在教程。

在我看來,盡管假定的返回文本為JSON,但Angular並未通過錯誤代碼將響應讀取為數​​組。 我已經查詢了這個問題,但似乎無法獲得正確處理我的代碼的答案。

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

您從服務返回整個json響應,而不僅僅是食譜數組。 您不能使用* ngFor迭代對象。 如下更改this.recipes =配方

getRecipes(): void {
        this.recipeService.getRecipes().subscribe(recipes =>
        if(recipes){
          this.recipes = recipes.Recipes;
         }
        );
      }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM