2016-04-05 12 views
7

Grazie al tutorial sulla pagina Angular 2 denominata "Tour of Heroes", sono riuscito a creare un'applicazione Angular 2 semplice. Quindi utilizzando Enitity Framework ho deciso di creare un database. E riempi la lista degli eroi da essa (non dal file). Ho creato Web Api Controller e ho aggiunto il metodo get semplice. Quindi in hero.service.ts chiamo questo metodo per ottenere l'elenco degli eroi. Quando pranza la mia app mostra la lista degli eroi ma senza valori (nome e id sono vuoti). Quando eseguo il debug dell'applicazione nel browser, è possibile vedere l'oggetto this.heroes in heroes.component.ts contenente i dati corretti. Quindi che sta succedendo? Perché non sono visualizzati name e id?Ottenere dati da API Web in 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; 
} 

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

eroe Entity:

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

JSON recuperato dal controller Web API:

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

Hai una risposta adeguata in console? Converti la risposta in CamelCase o qualcosa del genere? in html metti '{{heroes | json}}' e dimmi cosa ottieni? – micronyks

+0

Sì nella console dice lo stato: OK. E posso aprire il json in una nuova scheda e vedere i valori come sopra. Quando metto '{{heroes | json}}' Non vedo nulla ... – SteppingRazor

+0

Hai qualche errore? – micronyks

risposta

1

Nel mio caso il problema era legato al Visual Studio 2015 bug. Non c'era nulla di sbagliato nel codice stesso. A volte le modifiche apportate in vs non sono state aggiornate nel browser. Aggiornamento rispetto all'ultima versione aiutato.

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

No, l'operatore Elvis non sarà d'aiuto. La console non genera alcun errore, quindi il valore non è nullo almeno come 'hero'. – SteppingRazor

+0

'{value => this.heroes = value, console.log (this.heroes)}, ...' cosa ottieni in console? – micronyks

+0

dice 'undefined' – SteppingRazor

0

Prova questo: public heroes: Hero[] = [];