2017-06-01 1 views
1

Hallo arbeite ich an AngularJS Komponente, brauche Hilfe wie $ Watch innerhalb Konstruktor() wie unten zu verwenden Ich habe meine Code-Struktur beigefügt.

import template from './Mypage.component.html'; 
export const MyComponent = { 
template, 
bindings: { 
    myData: '<' 
}, 
controller: class MyController { 
    constructor($scope) { 
    $scope.$watch(() => this.myData, newVal => { 
    this._myFunction(); 
    }); 
    } 
} 

Antwort

0

Sie sollten $scope Abhängigkeit innerhalb $inject Array hinzufügen und es in Konstruktor funktionieren sollte. Aber bitte finden Sie unter Vorschlag.

controller: class MyController { 
    $inject = ['$scope']; 
    constructor($scope) { 
    $scope.$watch(() => this.myData, newVal => { 
     this._myFunction(); 
    }); 
    } 
} 

Wir alle wissen, $watch tut Feuer auf jedem Zyklus verdauen data bidnings auf Seite zu aktualisieren und es ist für die Leistung Grund schlecht. Eher könnten Sie $onChanges Lifecycle Hook von angularjs Komponente verwenden, so dass nur Feuer wird, wenn Bindings Wert geändert wird

controller: class MyController { 
    constructor($scope) {} 
    $onChanges(newVal) { 
    this._myFunction(); 
    } 
} 
0

Verwenden $onChanges() Methode statt $scope.$watch()

class MyController { 
    constructor() { 
    // Your constructor... 
    } 

    $onChanges(changedObj){ 
    // Expect myData changes 
    console.log(changedObj) 
    } 
} 

Mehr Infos here