2016-04-05 17 views
7

"Tour of Heroes" adlı Angular 2 sayfasındaki eğitici sayesinde, basit bir Angular 2 uygulaması oluşturmayı başardım. Sonra Enitity Framework kullanarak bir veritabanı oluşturmaya karar verdim. Ve kahramanlar listesini doldurun (dosyadan değil). Web Api Controller'ı oluşturdum ve basit get metodu ekledim. Ardından, hero.service.ts içinde kahramanların listesini almak için bu yöntemi çağırırım. Uygulamamı öğle yemeği yediğimde, kahramanların listesini gösterir, ancak herhangi bir değer içermez (isim ve kimlik boş). Uygulamamda tarayıcımda hata ayıkladığımda nesnesini heroes.component.ts doğru veride görebiliyorum. Peki neler oluyor? Neden name ve id gösterilmiyor?Angular 2'de Web API'sinden veri alma

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; 
} 

Web API Denetleyici:

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; 
     } 
    } 
} 

Kahraman Varlık: WEB API Kontrolörü alınan

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

JSON:

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

Konsolda uygun yanıt alıyor musunuz? Cevabı CamelCase'e veya başka bir şeye dönüştürüyor musunuz? html'de '{{heroes | json}}' yazıp neye ulaşıyorsunuz? – micronyks

+0

Evet, konsolda durum yazıyor: Tamam. Ve jsonu yeni sekmede açabilir ve yukarıdaki gibi değerleri görebilirim. Ben {{heroes | json}} 'i koyduğumda hiçbir şey göremiyorum ... – SteppingRazor

+0

Herhangi bir hata var mı? – micronyks

cevap

1

konu visual studio 2015 hata ilgiliydi. Kodun kendisi ile yanlış bir şey yoktu. Bazen, vs'de yapılan değişiklikler tarayıcıda yenilenmemiştir. En son sürüme güncellemeye yardım edildi.

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

Hayır, Elvis operatör burada yardımcı olmaz. Konsol herhangi bir hata atmaz, böylece değer en azından "kahraman" değildir. – SteppingRazor

+0

'{value => this.heroes = değer, console.log (this.heroes)}, ...' konsolda ne var? – micronyks

+0

'undefined' – SteppingRazor

0

bu deneyin: Benim durumumda public heroes: Hero[] = [];