import {Component} from 'angular2/core';
@Component({
selector: 'my-app',
template: '<h1>{{title}}</h1>'
})
export class AppComponent {
title = "Hello world!"
}
...
<body>
<my-app>Loading...</my-app>
</body>
...
import {Injectable} from 'angular2/core';
import {Observable} from 'Rxjs/Observable';
@Injectable()
export class HelloWorldService {
getHelloWorld() {
return Observable.of("Hello world");
}
}
import {Component, OnInit} from 'angular2/core';
import {HelloWorldService} from './hello-world.service';
@Component({
selector: 'my-app',
template: '<h1 *ngIf="title">{{title}}</h1>'
})
export class AppComponent implements OnInit {
title;
constructor(private helloService: HelloWorldService) {}
ngOnInit() {
this.helloService.getHelloWorld().subscribe(hello => this.title = hello);
}
}
import {Component, OnInit} from 'angular2/core';
import {HelloWorldService} from './hello-world.service';
@Component({
selector: 'my-app',
template: '
<h1 *ngIf="title">{{title}}</h1>
<div *ngFor="#hello of hellos">{{hello}}</div>
<button (click)="addHello()">add hello </button>
'
})
export class AppComponent implements OnInit {
title: string;
hellos: string[] = [];
constructor(private helloService: HelloWorldService) {}
ngOnInit() {
this.helloService.getHelloWorld().subcribe(hello => this.title = hello);
}
addHello() {
this.helloService.getHelloWorld().subsribe(hello => this.hellos.push(hello));
}
}
import {Injectable} from 'angular2/core';
import {Observable} from 'Rxjs/Observable';
import 'rxjs/map';
import {Http} from 'angular2/http'
@Injectable()
export class HelloWorldService {
constructor(http: Http) {}
private helloWorldApi: string = ...
getHelloWorld() {
return http.get(this.helloworldApi)
.map(response => response.json().hello)
.catch(Observable.throw(error || "Server error");
}
}
// Hello world API response
// {
// hello: "Hello world!"
(( }