处理服务和控制器数据之间的引用时遇到问题
// We have a service that we use to store id and some other data
app.service('testService', function ($http, serverURL) {
var self = this;
self.data = {
id: null,
token: null,
....
};
self.initMe = function () {
return $http({
method: 'GET',
url: serverURL + '/initMe/' + '?token=' + self.data.token
});
};
return self;
});
meModule.controller('MeCtrl', function (testService, ...) {
$scope.me = testService.data; // we make a connection between the scope and the controller
$rootScope.$on('initMe', function (e, data) {
testService.initMe().success(function (data, status, headers, config) {
// typeof(data.result) === 'object'
// $scope.me = data.result; // Doesn't work
// OR
// testService.data = data.result; // Doesn't work
testService.data = data.result; //
$scope.me = testService.data; // It works, but we have to recover
// the references between scope and service
});
});
}
问题
- 为什么我们在 $scope.me = data.result 或 meService.data = data.result; 中失去范围和服务之间的连接?
- 也许还有其他更好的方法可以从外部 API(获取请求)更新服务中的数据?