Angular 1.x コードを移行して、 $scope の使用を避け、コントローラーを構文として使用する、より新しい、より好ましい構文を使用しています。ただし、サービスからデータを取得する際に問題があります。
これが私の例です:
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>
私が抱えているこの問題は、データが $$state の子であるため、userService.async から返されたデータが、データを取得するためにドリルダウンできないように見えるオブジェクトであることです。ビューで使用されているようです。
これが Controller As/$scope-less 構文でサービスを使用する適切な方法でない場合、適切な方法は何ですか?