我正在尝试学习新的组件语法。如果我在控制器中静态设置一个用户变量,它会工作,我会在页面上看到数据。如果我尝试从服务获取相同的数据,则不会显示数据。在将数据分配给 this.user 变量后,我在 then promise 中看到数据。
我创建了一个 plunkr 来向您展示我正在尝试的内容。
http://plnkr.co/BGXesnKBmQGUlVH33jNa
angular.module('myWebApp', ['myModule']);
angular.module('myModule', []);
angular.
module('myModule').
component('myComponent', {
controller: ['myService', function myController(mySvc) {
mySvc.getUser().then(function (data) { // This gets data but does not populate view. Why?!
this.user = {
name: 'Joe',
last: 'Shmoe'
};
console.log(user); // Populated with data from service
});
// Comment out above and uncoment this and it works!
// this.user = {
// name: 'Joe',
// last: 'Shmoe'
// };
}],
template: 'Hello, {{ $ctrl.user.name }}!',
});
angular.
module('myModule').
factory('myService', ['$timeout', function ($timeout) {
function getUser() {
// Simulate http get
return $timeout(function() {
return {
name: 'Joe',
last: 'Shmoe'
};
}, 1000);
}
return {
getUser: getUser
};
}]);
正如llp指出的那样,this.user
指向函数的this
,所以你需要做的是在函数外部和控制器内部的变量中定义this
,就像这样(plunker):
angular.module('myWebApp', ['myModule']);
angular.module('myModule', []);
angular.
module('myModule').
component('myComponent', {
controller: ['myService', function myController(mySvc) {
var me = this;
mySvc.getUser().then(function (data) { // This gets data but does not populate view. Why?!
me.user = {
name: 'Joe',
last: 'Shmoe'
};
console.log(me.user); // Populated with data from service
});
// Comment out above and uncoment this and it works!
// this.user = {
// name: 'Joe',
// last: 'Shmoe'
// };
}],
template: 'Hello, {{ $ctrl.user.name }}!',
});
angular.
module('myModule').
factory('myService', ['$timeout', function ($timeout) {
function getUser() {
// Simulate http get
return $timeout(function() {
return {
name: 'Joe',
last: 'Shmoe'
};
}, 1000);
}
return {
getUser: getUser
};
}]);
因为 then
内函数中的 this
变量与 controller
的this
不一样,我建议你使用保持this
不变的箭头函数来解决这个问题:
angular.module('myWebApp', ['myModule']);
angular.module('myModule', []);
angular.
module('myModule').
component('myComponent', {
controller: ['myService', function myController(mySvc) {
mySvc.getUser().then((data) => { // Changed here!
this.user = {
name: 'Joe',
last: 'Shmoe'
};
console.log(this.user); // Populated with data from service
});
// Comment out above and uncoment this and it works!
// this.user = {
// name: 'Joe',
// last: 'Shmoe'
// };
}],
template: 'Hello, {{ $ctrl.user.name }}!',
});
angular.
module('myModule').
factory('myService', ['$timeout', function($timeout) {
function getUser() {
// Simulate http get
return $timeout(function() {
return {
name: 'Joe',
last: 'Shmoe'
};
}, 1000);
}
return {
getUser: getUser
};
}]);
更新的普伦克