0
什么是角度2等效$scope.watch
?
我使用$scope.watch
观察来自我的控制器中使用的外部服务对象的更改。
我知道$scope
不适用了,但如何设置手表功能?
什么是角度2等效$scope.watch
?
我使用$scope.watch
观察来自我的控制器中使用的外部服务对象的更改。
我知道$scope
不适用了,但如何设置手表功能?
你可以使用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
}
}
}
感谢您的回答。我尝试了你的方法,但没有奏效。我发布了我在上面的答案中使用的代码。你能让我知道我做错了什么吗? – nearpoint
不客气!你发布的代码在哪里?我看不到它... –