The DataService doesn't appear to be calling the Controller.
data.service.ts
import { Injectable, Inject } from 'angular2/core'; import { Http, Response } from 'angular2/http'; import 'rxjs/add/operator/map'; import {Observable} from 'rxjs/Observable'; import { TodoItem } from './TodoItem'; @Injectable() export class DataService { constructor( @Inject(Http) public http: Http) { this.http = http; } getItems(): Observable<TodoItem> { return this.http.get('/api/todo').map((res: Response) => res.json()); } addItem(item) { this.http.post('/api/todo', item); } }
add-item.component.ts
import { Component, Inject } from 'angular2/core'; import { TodoItem } from './TodoItem'; import { DataService } from './data.service'; @Component({ selector: 'add-item', template: ` <input #item><button (click)=addItem(item.value)>Add</button> ` }) export class AddItemComponent { private item: TodoItem; constructor( @Inject(DataService) private dataService: DataService) { this.dataService = dataService; this.item = { Key: '', Name: '' }; } addItem(item: string) { if (item) { this.item.Name = item; this.dataService.addItem(this.item); } } }
app.component.ts
import { Inject, Component } from 'angular2/core';
import { DataService } from './data.service';
import { HTTP_BINDINGS } from 'angular2/http';
import { TodoItem } from './TodoItem';
import { AddItemComponent } from './add-item.component';
@Component({
selector: 'app',
bindings: [DataService, HTTP_BINDINGS],
directives: [
AddItemComponent
],
template: `<h1>Hello World</h1>
<li *ngFor="#item of items">
<span>{{item.Name}} {{item.Key}}</span>
</li>
<h4>Create</h4>
<p><i>Add a new hero</i></p>
<div><add-item></add-item></div>
`
})
export class AppComponent {
public items: TodoItem[];
constructor( @Inject(DataService) public dataService: DataService) {
this.dataService = dataService;
}
ngOnInit() {
this.dataService.getItems()
.subscribe((items: TodoItem[]) => {
this.items = items;
});
}
}