我没有得到任何错误,JSON从后端返回正常。 问题是,我在下面的代码中做错了什么?
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>
答案 0 :(得分:1)
{{prof.name}}
应该是
{{prof.Name}}
答案 1 :(得分:1)
您的图片提示数组为null
,其中包含:
...ng-for-of: null
所以除了Günther提到{{prof.name}}
应该是{{prof.Name}}
之外,
您的JSON包含Data
,(带大写字母),但在您的get-request中,您使用的是data
。这实际上区分大小写,因此以下行
.then(response => response.json().data as Profile[])
应该是:
.then(response => response.json().Data as Profile[])
应正确填充数组:)