부모 컨트롤러가 UserEditCtrl
이고 자식 컨트롤러가 EditUserCtrl
입니다. 내 부모 컨트롤러의 내부 나는 서비스를 통해 사용자 개체 당기는 오전 :각도 '컨트롤러로'구문에서 'this'키워드에 대한 혼동
userMgmtSvc.user(scope.editUserId).then(function(data) {
this.user = data;
});
가 그럼 난 다른 변수에 내 사용자 개체의 속성을 설정합니다.
Cannot read property 'user' of undefined.
내가 this
로 설정 객체를 참조하는 방법에 대한 혼란 스러워요 :
this.selectedRoles = this.user.roles;
는하지만이 오류가 발생합니다. 예를 들어, 나는 단지 console.log 객체를 어떻게 만듭니 까? console.log('user', this.user);
반환 정의되지 않은 때문에 :
(
function (app) {
/* @fmt: off */
'use strict';
// @fmt:on
app.controller('UserEditCtrl', ['$scope', '$http', 'userMgmtSvc', 'createUserSvc', 'authSvc', '$state', '$timeout', '$location', '_',
function (scope, http, userMgmtSvc, createUserSvc, authSvc, state, timeout, location, _) {
userMgmtSvc.user(scope.editUserId.id || sessionStorage.getItem('editUser')).then(function(data) {
this.user = data;
console.log('user', this.user);
// GET states
createUserSvc.states().then(function(data) {
this.states = data;
console.log(this.states);
});
// GET countries
createUserSvc.countries().then(function(data) {
this.countries = data;
});
// GET roles
createUserSvc.roles().then(function(data) {
this.roles = data;
});
// GET insurance groups
createUserSvc.insuranceGroups().then(function(data) {
this.insuranceGroups = data;
});
this.selectedRoles = this.user.roles;
});
}]);
}(window.app)
);
합니다. [올바른 'this'/콜백 내 컨텍스트에 액세스하는 방법?] (https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback)을 참조하십시오. . 또한,'this.user.roles'를 읽으려고 할 때'then' 콜백은 아직 실행되지 않았을 가능성이 높기 때문에 'this'가 설정되어 있어도 값을 설정할 수 없습니다. 올바른 개체를 참조했습니다. 더 나은 결과를 얻으려면 여기에 설명 된 ** 완전한 *** 예제를 제공해야합니다. https://stackoverflow.com/help/mcve –
Felix의 말. 'then()'의 함수를'this '에 항상'.bind()'하여 올바른 키워드가되도록 할 수 있습니다. – Jhecht