2017-05-04 206 views
1

我在将数据库中的信息显示到角2 * ngFor循环时出现问题。这是到目前为止我的代码:Angular 2/ASP.NET Core * ngFor循环问题

对.NET核心控制器:

 // GET: api/Hats 
    [HttpGet("GetHats")] 
    public IEnumerable<Hat> GetHats() 
    { 
     return _context.Hat; 
    } 

帽子list.component.ts:

//Imports from @Angular 
import { Component, OnInit } from '@angular/core'; 
import { Http } from '@angular/http'; 

//Other imports 
import { HatListService } from '../service/service.component'; 
import Hat = App.Models.IHat; 
//Component Config 
@Component({ 
    selector: 'hat-list', 
    templateUrl: './hat-list.component.html', 
    providers: [HatListService] 
}) 
//Class 
export class HatListComponent implements OnInit { 

    public Hats: any[]; 
    constructor(public _hatListService: HatListService) { 

    } 


    //OnInit 
    ngOnInit() { 
     this.getAllHats(); 
    } 

    //Get All 
    getAllHats() { 
     //debugger 
     this._hatListService.getHatList().subscribe(foundHats => 
      this.Hats = foundHats 
     ); 
    } 
} 

service.component.ts

//imports from Angular 
import { Injectable, Component } from '@angular/core'; 
import { Http, Request, RequestMethod, Response, RequestOptions, Headers } from '@angular/http'; 
import 'rxjs/Rx'; 
import { Observable } from 'rxjs/Observable'; 
//Other imports 
import Hat = App.Models.IHat; 
@Component({ 
    providers: [Http] 
}) 
//Exported class 
@Injectable() 
export class HatListService { 

    public headers: Headers; 

    constructor(private _http: Http) { 
    } 

    public _getUrl: string = '/api/Hats/GetHats'; 

    //Get 
    getHatList(): Observable<Hat[]> { 
     //debugger 
     return this._http.get(this._getUrl).map(res => <Hat[]>res.json()) 
      .catch(this.handleError); 
    } 


    private handleError(error: Response) { 
     return Observable.throw(error.json().error || 'Opps!! Server error'); 
    } 
} 

帽子list.component.html:

<table class="table table-hover table-striped table-responsive"> 
    <thead> 
     <tr> 
      <th>Name</th> 
      <th>Color</th> 
      <th>Count</th> 
      <th></th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr *ngFor="let hat of Hats""> 

      <td>{{hat.Name}}</td> 
      <td>{{hat.Color}}</td> 
      <td>{{hat.Count}}</td> 
      <td> 
       <a class="glyphicon glyphicon-remove" (click)="delete(hat)"></a> 
      </td> 
     </tr> 
    </tbody> 
</table> 

图片表 enter image description here

的* ngFor的收到
值。

enter image description here

我知道请求到数据库中发生非同步和数据已经返回,因此* ngfor循环火灾之前显示的一个问题可能没有信息。但网上的不同文章说,* ngFor循环不应该触发,除非迭代器有一个值。奇怪的是,当我通过SSMS手动更新数据库时,* ngfor识别添加的内容添加创建additioanl行。我究竟做错了什么。

感谢所有的帮助!

+1

你可以显示你的'Hat'类吗?不确定100%,但我想问题是你使用了不正确的变量名称,即{{hat.Name}}而不是{{hat.name}}。 –

+0

糟糕的格式的Soory。试图格式化为代码# 声明模块App.Models {0}接口IHat { Id:number; 名称:string; 颜色:string; 计数:数字; } }' – AllramEst

+0

你有我最大的thanx先生!!这样的noobie错误。将界面属性更改为小型凝视字母。它的工作。 – AllramEst

回答

1

模板中使用了错误的变量名称,即{{hat.Name}}而不是{{hat.name}}