2017-02-12 5 views
1

エラーが発生せず、JSONがバックエンドから返されます。 質問は、以下のコードで何か間違ったことをしましたか?角2 NForループが表示されない

JSON

{ 
    "Data": [{ 
     "ProfileId": "121212", 
     "Name": "Charles", 
     "info": { 
      "rating": "0", 
      "plot": "Nothing happens at all." 
     } 
    }] 
} 

Home.Component.ts

import { Component, OnInit } from "@angular/core"; 
import { HomeService } from './home.service'; 
import { Profile } from './profile'; 
import 'rxjs/add/operator/map'; 
@Component({ 
    moduleId: module.id, 
    selector: "home-page", 
    templateUrl: "home.component.html", 
    styleUrls: ["home.component.css"], 
    providers: [ HomeService ] 
}) 

export class HomeComponent implements OnInit { 
    constructor(private service: HomeService) {} 

    Profiles: Profile[]; 

    getProfile(): void { 
     this.service 
      .getData() 
      .then(profiles => this.Profiles = profiles); 

    } 
    ngOnInit(){ 
     this.getProfile(); 
    } 

} 

Home.service.ts

import {Injectable } from "@angular/core"; 
import {Headers, Http, Response} from '@angular/http'; 
import 'rxjs/add/operator/toPromise'; 
import { Profile } from './profile'; 

@Injectable() 
export class HomeService { 
    private usersUrl = 'http://localhost:8888/'; 
    private headers = new Headers({'Content-Type': 'application/json'}); 
    constructor(private http: Http) {} 

    getData(): Promise<Profile[]> { 
     return this.http.get(this.usersUrl) 
      .toPromise() 
      .then(response => response.json().data as Profile[]) 
      .catch(this.handleError); 

     //let err = new Error('Cannot get object of this type'); 

    } 


    private handleError(error: any): Promise<any> { 
     console.error('An error occurred', error); // for demo purposes only 
     return Promise.reject(error.message || error); 
    } 
} 

home.component.html

<h2>HOME</h2> 
 
<ul> 
 
    <li *ngFor="let prof of Profiles;"> 
 
     {{prof.name}} 
 
    </li> 
 
</ul>

Rendered as this in browser

+0

どこに問題がありますか? – MChaker

+0

@MChaker、申し訳ありませんが、編集で追加していました。投稿したコードに明らかなことはありませんが、それは動作しない原因になるでしょうか? – iWheezy

答えて

1
{{prof.name}} 

{{prof.Name}} 
1

あなたの絵が持つ配列がnullあることのヒントを与えるようになります。

...ng-for-of: null 

そのようなGüntherの言及の他に{{prof.name}}{{prof.Name}}、 あなたのJSONはData(大文字)を保持していますが、あなたの入手リクエストではdataを使用しています。次の行

.then(response => response.json().data as Profile[]) 

があるべきように、これは実際には、大文字と小文字を区別している:正しく配列を移入する必要があり

.then(response => response.json().Data as Profile[]) 

:)

関連する問題