2017-05-04 203 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}}