1

这会成功显示 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());
    }
}
4

2 回答 2

2

使用 Angular 2 Beta 1,我需要添加绑定而不是提供者,并将 DataService 注入到构造函数中。

app.component.ts

import { Inject, Component } from 'angular2/core';
import { DataService } from './data.service';
import { HTTP_BINDINGS } from 'angular2/http';

@Component({ 
    selector: 'app',
    bindings: [DataService, HTTP_BINDINGS],
    template: `<h1>Hello World</h1>
<li *ngFor="#customer of customers">
  <span>{{customer.firstName}}</span> 
</li>
`
})
export class AppComponent {
    private customers: any[];
    constructor( @Inject(DataService) public dataService: DataService) {
        this.dataService = dataService;
    }


    ngOnInit() {
        this.dataService.getCustomers()
            .subscribe((customers: any[]) => {
                this.customers = customers;
            }); 
    }
}
于 2016-01-18T07:17:22.517 回答
1

您需要将DataService注册为组件的提供者之一。

import { Component } from 'angular2/core';
import { DataService } from './data.service';

@Component({ 
  selector: 'app',
  providers: [DataService], 
  template: `<h1>Hello World</h1>
<li *ngFor="#customer of customers">
  <span>{{customer.firstName}}</span> 
</li>
`
})
export class AppComponent {

    customers: any[];

    constructor(public dataService: DataService) { }

    ngOnInit() {
        this.dataService.getCustomers()
            .subscribe((customers: any[]) => {
                this.customers = customers;
            });
    }
}
于 2016-01-16T20:43:33.313 回答