我正在关注Angular Tour of Heroes教程,并试图实现类似的东西,但我遇到了问题。我想我可能会遗漏一些东西,但我没有收到错误消息,也不知道如何调试。
代码编译没有问题。当我在浏览器中运行应用程序时,它不显示应该显示成员数据的任何内容。在控制台中,我看到没有错误。
memberlist.component.ts
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
import { Member } from './member';
import { MembersService } from './members.service';
@Component({
selector: 'member-list',
template: `
<ul *ngFor="let member of members; let i = index;">
<li>
<strong>{{member.name}}</strong>
</li>
</ul>
{{members}}
`
})
export class MemberListComponent {
members: Member[];
constructor(private memberService: MembersService) {}
ngOnInit(): void {
this.getMembers();
}
getMembers(): void {
this.memberService
.getMembers()
.then(members => this.members = members);
}
}
members.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Member } from './member';
@Injectable()
export class MembersService {
private url = 'http://localhost:8080/members'; // URL to web api
constructor(private http: Http){}
getMembers(): Promise<Member[]> {
return this.http.get(this.url)
.toPromise()
.then(response => response.json().data as Member[])
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.log('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
member.ts
export class Member {
constructor(
public id: number,
public name: string,
public color: string
){}
}
我在浏览器中输入localhost:8080 / members时的JSON字符串:
[{ “ID”:0, “名称”: “鲍勃”, “色彩”: “蓝”},{ “ID”:0, “名称”: “鲍勃”, “色彩”: “蓝” },{ “ID”:0, “名称”: “鲍勃”, “色彩”: “蓝”},{ “ID”:0, “名称”: “鲍勃”, “色彩”: “红”}]