2016-06-07 4 views
1

기본 구성 요소를 사용할 수 있지만 약속을 반환하는 $ http (users.get())를 통해 일부 데이터를로드하려고합니다 (데이터가 console.log (this.data)에 표시됩니다.)하지만 데이터가(1.5) 각 구성 요소에 데이터를로드하는 방법은 무엇입니까?

.component('mrcUserInfo', { 
bindings: { 
    email: '<', 
    first_name: '<', 
    last_name: '<' 
}, 
templateUrl: 'components/userInfo.html', 
controller: function(users) { 
    var scope = {}; 
    scope.thisId = 1; 
    this.miketest = 'this is miketest'; 

    users.get(scope) // basically does a $http()... 
    .then(function(data) { 
     this.data = data.data; 
     this.email = data.email; 
     this.miketest = 'this is mike 2'; 

     console.log('user?'); 
     console.log(this.data); 
    }); 
} 

왜?. 구성 요소 템플릿을 제작하지 않습니다 그리고 내 템플릿이

this is userInfo.html: 
{{ $ctrl.miketest }} 

템플릿 표시 '이 miketest이다'하지만이 마이크 2 '표시하지 않습니다있다 '

감사의 말씀 감사합니다. 마이크

답변

1

특히 비동기 코드에서 this을 사용할 때주의하십시오. 특정 경우에 this은 콜백에 window 개체가 될 것이므로 실제로 컨트롤러가 아닌 창에 miketest 변수가 설정되어 있습니다. 당신이 할 수있는, 당신은 BabelJS 같은 것을 사용하는 경우,

users.get(scope) // basically does a $http()... 
    .then(function(data) { 
    this.data = data.data; 
    this.email = data.email; 
    this.miketest = 'this is mike 2'; 

    console.log('user?'); 
    console.log(this.data); 
    }.bind(this)); 

또한, 현대 자바 스크립트 기능을 사용할 수 있습니다 : 바인딩을 this를 명시 적으로

var ctrl = this; 
users.get(scope) // basically does a $http()... 
    .then(function(data) { 
    ctrl.data = data.data; 
    ctrl.email = data.email; 
    ctrl.miketest = 'this is mike 2'; 

    console.log('user?'); 
    console.log(ctrl.data); 
    }); 

또는를 :

당신이 중 하나를 수행 할 수 있습니다 이중 화살표 함수를 사용하여 을 어휘 범위에 바인딩하십시오.

users.get(scope) // basically does a $http()... 
    .then((data) => { 
    this.data = data.data; 
    this.email = data.email; 
    this.miketest = 'this is mike 2'; 

    console.log('user?'); 
    console.log(this.data); 
    }); 
+0

그게 고마워! –

관련 문제