这会成功显示 Hello World,因此 app.component.ts 可以正确引导。DataService 没有返回数据,或者无法显示。没有编译器错误。TypeScript 中是否有一个弹出窗口,例如 JavaScript 中的 alert(),我可以快速检查数据服务是否正在返回数据?
app.component.ts
import { Component } from 'angular2/core';
import { DataService } from './data.service';
@Component({
selector: 'app',
template: `<h1>Hello World</h1>
<li *ngFor="#customer of customers">
<span>{{customer.firstName}}</span>
</li>
`
})
export class AppComponent {
public dataService: DataService;
customers: any[];
constructor() { }
ngOnInit() {
this.dataService.getCustomers()
.subscribe((customers: any[]) => {
this.customers = customers;
});
}
}
数据服务.ts
import { Injectable } from 'angular2/core';
import { Http, Response } from 'angular2/http';
import 'rxjs/add/operator/map';
@Injectable()
export class DataService {
public http: Http
constructor() { }
getCustomers() {
return this.http.get('customers.json')
.map((res: Response) => res.json());
}
}