我正在迁移我的Angular 1.x代码以使用避免使用$ scope并使用控制器作为语法的更新,更喜欢的语法。虽然我从服务中获取数据时遇到了问题。AngularJS Ctrl作为语法与服务
这里是我的例子:
var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl', ['$http', '$location', 'userService',
function($http, $location, userService) {
this.name = 'John Doe';
// this.userData = {
// }
this.userData = userService.async().then(function(d) {
return d;
});
console.log(this.userData);
}
]);
myApp.service('userService', function($http) {
var userService = {
async: function() {
// $http returns a promise, which has a then function, which also returns a promise
var promise = $http.get('https://jsonplaceholder.typicode.com/users').then(function(response) {
// The then function here is an opportunity to modify the response
// console.log(response);
// The return value gets picked up by the then in the controller.
return response.data;
});
// Return the promise to the controller
return promise;
}
};
return userService;
});
<body ng-app="myApp">
<div id="ctrl-as-exmpl" ng-controller="MainCtrl as mainctrl">
<h1>Phone Numbers for {{mainctrl.name}}</h1>
<button ng-click="">newest</button>
<p>{{mainctrl.userData}}</p>
<ul>
<li ng-repeat="users in mainctrl.userData">{{users.phone}} -- {{users.email}}</li>
</ul>
</div>
</body>
我遇到这个问题是从userService.async返回的数据是一个对象,我似乎无法深入通以获取数据,因为数据是$$状态的孩子,这在视图中似乎不能使用。
如果这不是在Controller As/$ scope-less语法中使用服务的正确方法,那么正确的方法是什么?
活生生的例子在这里:http://plnkr.co/edit/ejHReaAIvVzlSExL5Elw?p=preview
如果我注销'this'和占位符值(在我的plnkr中:http://plnkr.co/edit/KBnz7yQkyBp3B8MPFpYd?p=预览我正在使用'vm'),它们都有来自userService $ http调用的返回数据。但是,只有使用占位符才能使数据在视图中呈现。这是为什么? – TWLATL
由于JS作用域,当你在'then'中的匿名函数中时,''this'关键字处理匿名函数,这就是为什么你需要将控制器函数实例的'this'设置为一个变量,所以该实例将在控制器内的所有“子”功能中可用。 –