从Angular 2中的Web API获取数据

时间:2016-04-05 12:56:18

标签: json entity-framework asp.net-web-api angular

感谢Angular 2页面上的教程"Tour of Heroes",我设法创建了一个简单的Angular 2应用程序。然后使用Enitity Framework我决定创建一个数据库。并从中填充英雄列表(不是从文件中)。我创建了Web Api Controller并添加了简单的get方法。 然后在hero.service.ts我调用此方法以获取英雄列表。当我在我的应用程序午餐时,它会显示英雄列表,但没有任何值(名称和ID为空白)。当我在浏览器中调试我的应用程序时,我可以看到this.heroes中的heroes.component.ts对象包含正确的数据。那么发生了什么?为什么不显示nameid

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控制器:

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

英雄实体:

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

从WEB API控制器检索到的JSON:

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

3 个答案:

答案 0 :(得分: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")
         );
 }

答案 1 :(得分:0)

试试这个:public heroes: Hero[] = [];

答案 2 :(得分:0)

就我而言,这个问题与visual studio 2015 bug有关。代码本身没有任何问题。有时在vs中所做的更改不会在浏览器中刷新。更新vs最新版本有所帮助。