【发布时间】:2016-05-19 17:07:19
【问题描述】:
$scope.watch 的 Angular 2 等价物是什么?
我使用$scope.watch 来观察控制器中使用的外部服务中对象的变化。
我知道$scope 不再适用但如何设置手表功能?
【问题讨论】:
标签: angular
$scope.watch 的 Angular 2 等价物是什么?
我使用$scope.watch 来观察控制器中使用的外部服务中对象的变化。
我知道$scope 不再适用但如何设置手表功能?
【问题讨论】:
标签: angular
您可以使用ngOnChanges 方法在任何绑定发生更改时收到通知:
@Component({
selector: 'my-cmp',
template: `<p>myProp = {{myProp}}</p>`
})
class MyComponent implements OnChanges {
@Input() myProp: any;
ngOnChanges(changes: {[propName: string]: SimpleChange}) {
console.log('ngOnChanges - myProp = ' +
changes['myProp'].currentValue);
}
}
但这取决于您的用例,因为您也可以利用(例如)表单控件来获得通知:
@Component({
selector: 'four',
directives: [MyDirective],
template: `
Hello, this is working! <br>
<textarea mydir [(ngModel)]="pp.status" [ngFormControl]="myCtrl">
</textarea>
`,
})
export class Four {
@Input() pp;
constructor() {
this.myCtrl = new Control();
this.myCtrl.valueChanges.subscribe(
(data) => {
console.log('Model change');
});
}
}
您还可以利用自定义EventEmitter,您可以在服务内订阅以在组件外部进行通知。
【讨论】:
您可以为此使用 rx.js 函数 Observable.of(something)。
import {Observable} from "rxjs/Rx";
class Example {
public test;
public watchTest;
constructor(){
this.setWatch()
this.seeWatch()
}
setWatch() {
this.watchTest = Observable.of(this.test);
}
seeWatch() {
this.watchTest.subscribe(data => {
data //this.test value
}
}
}
【讨论】:
of 适用于“单次”行为有意义的其他用例。