最接近ko.observable 的类似物是Subject 甚至BehaviorSubject,对于ko.computed,您可以使用Observable.combineLatest
这是一个hello world的例子:
import 'rxjs/add/operator/map';
import {Component} from '@angular/core';
import {Observable, BehaviorSubject} from "rxjs";
@Component({
selector: 'app-root',
template: `<div>
<button (click)="both()">both</button>
<button (click)="first()">first</button>
<button (click)="last()">last</button>
<button (click)="ageNow()">age</button>
<hr />
fullName: {{fullName | async}}
<hr />
age: {{age | async}}
</div>`
})
export class AppComponent {
firstName = new BehaviorSubject(''); // aka this.firstName = ko.observable('')
lastName = new BehaviorSubject('');
age = new BehaviorSubject(0);
fullName = Observable.combineLatest(this.firstName, this.lastName) // aka this.fullName = ko.computed(...)
.do(values => console.log('computed fired'))
.map(values => values.join(' ').trim());
both() {
this.first();
this.last();
}
first() {
this.firstName.next('foo ' + Date.now());
}
last() {
this.lastName.next('bar ' + Date.now());
}
ageNow() {
this.age.next(Date.now());
}
}
也许你会想让它与表单一起工作,那么示例将是这样的:
import 'rxjs/add/operator/map';
import {Component} from '@angular/core';
import {Observable, BehaviorSubject} from "rxjs";
import {FormGroup, FormControl, FormBuilder} from "@angular/forms";
@Component({
selector: 'app-root',
template: `<form [formGroup]="form">
<input formControlName="firstName" />
<input formControlName="lastName" />
{{fullName | async}}
</form>`
})
export class AppComponent {
form:FormGroup;
firstName = new FormControl('');
lastName = new FormControl('');
fullName = Observable.combineLatest(
this.firstName.valueChanges.startWith(''),
this.lastName.valueChanges.startWith('')
).map(values => values.join(' ').trim());
constructor(private fb:FormBuilder) {
this.form = fb.group({
firstName: this.firstName,
lastName: this.lastName
});
}
}
请注意,在表单示例中,我们关注的不是 FormControl,而是它在 valueChanges 流中的构建,我们还为它定义了初始值。
如果您不想处理模板中的| async 管道,您始终可以订阅您的流和它们的组件属性