2016-04-05 8 views
7

"Tour of Heroes"というAngular 2ページのチュートリアルのおかげで、簡単なAngular 2アプリケーションを作成することができました。 Enitity Frameworkを使用してデータベースを作成することにしました。そしてそれからヒーローのリストを記入します(ファイルからではありません)。 Web Api Controllerを作ってシンプルなgetメソッドを追加しました。 その後、hero.service.tsで私はこのメソッドを呼び出してヒーローのリストを取得します。私は私のアプリを昼食するとき、ヒーローのリストを表示しますが、値はありません(名前とIDは空白です)。ブラウザでアプリケーションをデバッグすると、this.heroesオブジェクトにheroes.component.tsというオブジェクトが正しいデータを含んでいることがわかります。では何が起こっているのですか? nameidが表示されないのはなぜですか?Web APIからAngular 2でデータを取得

hero.service.ts:

import {Injectable} from 'angular2/core'; 
import {HEROES} from './mock-heroes'; 
import {Hero} from './hero'; 
import {Http, Response} from 'angular2/http'; 
import 'rxjs/Rx'; 
import {Observable}  from 'rxjs/Observable'; 

@Injectable() 
export class HeroService { 

    public values: any; 

    constructor(public _http: Http) { } 

    private _heroesUrl = 'http://localhost:61553/api/values'; // URL to web api 

    getHeroes() { 
     return this._http.get(this._heroesUrl) 
      .map(res => <Hero[]>res.json()) 
      .catch(this.handleError); 
    } 
    private handleError(error: Response) { 
     console.error(error); 
     return Observable.throw(error.json().error || 'Server error'); 
    } 
} 

heroes.component.ts:

import {Component, OnInit} from 'angular2/core'; 
import {Router} from 'angular2/router'; 

import {Hero} from './hero'; 
import {HeroDetailComponent} from './hero-detail.component'; 
import {HeroService} from './hero.service'; 

@Component({ 
    selector: 'my-heroes', 
    templateUrl: 'templates/heroes.component.html', 
    styleUrls: ['styles/heroes-component.css'], 
    directives: [HeroDetailComponent] 
}) 

export class HeroesComponent implements OnInit { 

    constructor(private _heroservice: HeroService, private _router: Router) { } 

    errorMessage: string; 
    public heroes: Hero[]; 

    selectedHero: Hero; 

    ngOnInit() { 
     this.getHeroes(); 
    } 

    onSelect(hero: Hero) 
    { 
     this.selectedHero = hero; 
    } 

    getHeroes() { 
     this._heroservice.getHeroes() 
      .subscribe(
      value => this.heroes = value, 
      error => this.errorMessage = <any>error); 
    } 

    gotoDetail() { 
     this._router.navigate(['HeroDetail', { id: this.selectedHero.Id }]); 
    } 
} 

heroes.component.html:

<h2>My Heroes</h2> 
<ul class="heroes"> 
    <li *ngFor="#hero of heroes" [class.selected]="hero === selectedHero" (click)="onSelect(hero)"> 
     <span class="badge">{{hero.Id}}</span> {{hero.Name}} 
    </li> 
</ul> 
<div *ngIf="selectedHero"> 
    <h2> 
     {{selectedHero.Name | uppercase}} is my hero 
    </h2> 
    <button (click)="gotoDetail()">View Details</button> 
</div> 

hero.ts:

export class Hero { 
    Id: number; 
    Name: string; 
} 

ウェブAPIコントローラ:

using Microsoft.AspNet.Mvc; 
using System.Collections.Generic; 
using TestApplicationDataAccess; 
using TestApplicationDataAccess.Entities; 

namespace WebApplication2.Controllers 
{ 
    [Route("api/[controller]")] 
    public class ValuesController : Controller 
    { 
     private readonly TestAppDbContext _dbContext; 

     public ValuesController(TestAppDbContext dbContext) 
     { 
      _dbContext = dbContext; 
     } 

     // GET: api/values 
     [HttpGet] 
     public IEnumerable<Hero> Get() 
     { 
      return _dbContext.Heroes; 
     } 
    } 
} 

ヒーローエンティティ:WEB APIのコントローラから取得

namespace TestApplicationDataAccess.Entities 
{ 
    public class Hero 
    { 
     public int Id { get; set; } 
     public string Name { get; set; } 
    } 
} 

JSON:

[{"Id":1,"Name":"Superman"}] 
+0

コンソールで適切な応答を得られますか?レスポンスをCamelCaseなどに変換しますか? htmlに '{{heroes | json}}'を入れて何を得るのか教えてください。 – micronyks

+0

はい、コンソールにステータス:OKと表示されます。そして、私は新しいタブでjsonを開き、上記のような値を見ることができます。 {{英雄| json}}を置くと何も見えません... – SteppingRazor

+0

エラーが発生しますか? – micronyks

答えて

1

問題はVisual Studioの2015年のバグに関連していたが。コード自体に問題はありませんでした。ブラウザでvsで行った変更が更新されないことがあります。最新バージョンへのアップデートは助けになりました。

0
getHeroes() { 
     this._heroservice.getHeroes() 
      .subscribe(res=>{ 
      this.heroes=res; 
      console.log(this.heroes); // make sure you get data here. 
     }, 
     (err)=>console.log(err), 
     ()=>console.log("Done") 
     ); 
} 
+0

いいえ、エルヴィスのオペレーターはここでは助けません。コンソールはエラーを投げないので、値は少なくとも「ヒーロー」ではない。 – SteppingRazor

+0

'{値=> this.heroes = value、console.log(this.heroes)}、...'コンソールではどうしますか? – micronyks

+0

それは 'undefined 'と言います – SteppingRazor

0

これを試してみてください。私の場合はpublic heroes: Hero[] = [];

関連する問題