首页 文章

什么是$ scope.watch的Angular 2等价物? [重复]

提问于
浏览
1

这个问题在这里已有答案:

什么是Angular 2相当于 $scope.watch

我使用 $scope.watch 来观察控制器中使用的外部服务对象的更改 .

我知道 $scope 不再适用,但如何设置 Watch 功能?

2 回答

  • 2

    如果任何绑定已更改,您可以使用 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 ,您可以在服务中订阅以通知组件外部 .

  • 1

    您可以使用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
           }
        }
    
    }
    

相关问题