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
不客氣!你發佈的代碼在哪裏?我看不到它... –