首页 文章

如何在Angular 2中观看复杂对象,就像我们在Angular 1中使用$ watch一样

提问于
浏览
4

我们能够在复杂对象上应用 $watch ,如何在Angular 2中进行类似操作 .

Angular 1

$scope.data = {name : "somvalue"}
$scope.$watch('data.name', function(newValue, oldValue) {
    scope.counter = scope.counter + 1;
});

Angular 2

export class MyData{
   name: string;
} 

export class MyComponent implements OnInit {
   @Input() data: MyData;

   constructor(private ds: MyService){
      this.data = ds.data;
   }

   // $watch('data.name', function(newValue, oldValue) {
   //   scope.counter = scope.counter + 1;
   // });
}

现在如果 data.name 在服务中发生变化,如何观察组件本身的变化,请注意数据不是可观察的,它只是一个常规对象 .

Update

Please see Plunk for an example

提前致谢!!

3 回答

  • 0

    实现组件生命周期钩子“ngOnChanges”:

    import { OnChanges } from '@angular/core';
    
    @Component({
        selector: 'child',
        template: `
            <h2>Child component</h2>
            {{ person }}
        `
    })
    class ChildComponent implements OnChanges {
        @Input() person: string;
    
        ngOnChanges(changes: {[ propName: string]: SimpleChange}) {
            console.log('Change detected:', changes[person].currentValue);
        }
    
    }
    

    UPDATE

    我发现了一个可行的解决方法 . 实现DoCheck钩子而不是OnChanges .

    ngDoCheck() {
       if(!this.inputSettings.equals(this.previousInputSettings)) {
           // inputSettings changed
           // some logic here to react to the change
           this.previousInputSettings = this.inputSettings;
       }
    }
    

    请记住doCheck运行多次,如果错过使用会导致性能问题 .

  • 0

    Angular检查属性,如果它们在模板中绑定,则甚至是内部对象 .

    对于复杂对象,首选选项是使用 Observable 主动通知Angular2有关更改 .

    您还可以通过实现DoCheck来使用自定义更改检测

  • 1

    通常,除非您使用不同的更改检测策略,否则您的组件将侦听其所有对象变异 .

    import { OnChanges } from '@angular/core';
    
    @Component({
        selector: 'child',
        template: `
            <h2>Child component</h2>
            {{ person }}
        `,
       changeDetection:ChangeDetectionStrategy.OnPush/Default/CheckOnce/Always
    })
    class ChildComponent implements OnChanges {
        @Input() person: string;
    
        ngOnChanges(changes: {[ propName: string]: SimpleChange}) {
            console.log('Change detected:', changes[person].currentValue);
        }
    

    这个 :

    changeDetection:ChangeDetectionStrategy.OnPush/Default/CheckOnce/Always
    

    将定义当其中一个输入更新时组件的行为方式 .

    最重要的一个是OnPush和Default .

    OnPush表示仅当整个对象替换为新对象时更新组件,而Default表示如果任何嵌套值已更新(变异)则更新我 .

    并且,如果您不在组件中使用该对象,Angular将忽略并且不会更新视图(为什么会这样) .

    然后你可以轻松地挂钩到ngOnChange生命周期钩子,另一个答案建议得到更新 .

相关问题