【问题标题】:What is the Angular 2 equivalent of $scope.watch? [duplicate]$scope.watch 的 Angular 2 等价物是什么? [复制]
【发布时间】:2016-05-19 17:07:19
【问题描述】:

$scope.watch 的 Angular 2 等价物是什么?

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

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

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以使用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,您可以在服务内订阅以在组件外部进行通知。

    【讨论】:

    • 感谢您的回答。我试过你的方法,但没有奏效。我在上面的答案中发布了我使用的代码。你能告诉我我做错了什么吗?
    • 不客气!您发布的代码在哪里?我看不到它...
    【解决方案2】:

    您可以为此使用 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 适用于“单次”行为有意义的其他用例。
    猜你喜欢
    • 2016-11-02
    • 2018-06-17
    • 2016-06-05
    • 1970-01-01
    • 2011-12-26
    • 2015-06-13
    • 1970-01-01
    • 2019-12-23
    • 2016-04-06
    相关资源
    最近更新 更多