2017-12-01 17 views
0

私は大学のプロジェクトのためのWebアプリケーションを作成しています。このプロジェクトには、Web APIと、そのAPIに接続するFrontendという2つの部分があります。私が作っているウェブアプリはレシピのウェブサイトです。 Angularのような新しい技術に触れていないので、私は彼らのウェブサイト上で英雄ツアーのチュートリアルに参加し、それにかなりうまく対処しています。Angular2:NgForは配列などのIterableへのバインドのみをサポートします

しかし、ここで私は擬似データソースを使用せず、代わりにAPIを使用してデータを取得する必要があります。

(私はいくつかのコンポーネントを持っている、と私はアプリのこの部分のためのチュートリアルのHTTPセクションに関連するファイルは、recipe.service.tsrecipes.component.htmlを含めましたチュートリアルで編集する必要があるファイルのみ

Angularは、エラーコードによって配列として応答を読み取っていないようですが、返されるテキストは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> 

角度アプリを実行しているとき、私は、コンソールに取得していますエラー:

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" 
     } 
    ] 
} 

もし誰かが私を助けることができたら、それはすばらしいだろう。

感謝:)

EDIT - 私の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); 
    } 

} 
+1

あなたのコンポーネントは表示されませんが、レスポンスから配列を抽出していますか?私に聞こえるかもしれませんし、あなたの応答を反復しようとしています。これはオブジェクトです。 – Alex

+0

recipes.component.tsも追加できますか? – chayasan

+0

私の応答からアレイを抽出するにはどうすればいいですか? –

答えて

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

あなたの応答は、オブジェクト、配列ではありませんので。 this.recipesrecipes.Recipesに設定する必要があります。に従って:

+0

完全に動作するように見えます。どうもありがとうございました。 –

0

レシピ配列だけでなく、サービスからjson応答全体を返します。 * ngForを使用してオブジェクトを反復することはできません。 this.recipes = recipesを以下のように変更してください。

getRecipes(): void { 
     this.recipeService.getRecipes().subscribe(recipes => 
     if(recipes){ 
      this.recipes = recipes.Recipes; 
     } 
     ); 
     } 
関連する問題