使用 AngularJS,我尝试实现一个简单的服务,该服务从 REST 服务返回客户端
列表,然后在 Controller 中使用该列表。
我一直在思考如何正确地将数据传递到 Controller 。下面是我的服务,它可以很好地提取数据。我已验证数据存在
app.service('clientsService', ['$http', function ($http) {
var serviceBase = 'http://localhost:56879/api/';
this.getClients = function () {
return $http.get(serviceBase + 'clients').then(function (results) {
console.log(results.data);
return results.data;
});
};
}]);
接下来我尝试在 Controller 中使用它
app.controller('clientsController', ['$scope', 'clientsService', function ($scope, clientsService) {
this.clients = clientsService.getClients();
console.log(this.clients);
}]);
在此 Controller 中,this.clients
不包含数据,它只包含一个 try-catch block
Object {then: function, catch: function, finally: function}
catch: function (a){return this.then(null,
finally: function (a){function b(a,c){var d=e();c?d.resolve(a):d.reject(a);return d.promise}function d(e,g){var f=null;try{f=(a||c)()}catch(h){return b(h,!1)}return f&&P(f.then)?f.then(function(){return b(e,g)},function(a){return b(a,!1)}):b(e,g)}return this.then(function(a){return d(a,!0)},function(a){return d(a,!1)})}
then: function (b,g,h){var m=e(),u=function(d){try{m.resolve((P(b)?b:c)(d))}catch(e){m.reject(e),a(e)}},F=function(b){try{m.resolve((P(g)?g:d)(b))}catch(c){m.reject(c),a(c)}},v=function(b){try{m.notify((P(h)?h:c)(b))}catch(d){a(d)}};f?f.push([u,F,v]):k.then(u,F,v);return m.promise}
__proto__: Object
我还不太明白我实际上将数据从服务传递到 Controller 时做错了什么。
最佳答案
这是因为 getClients
方法返回 promise
,不是数据。该 promise 决定在回调中返回数据。您在控制台中看到的方法是服务方法返回的 Promise 对象的方法。所以你应该注册一个回调到 promise 的 then
方法:-
var _that = this;
clientsService.getClients().then(function(data) { //Runs when promise is resolved
_that.clients = data;
}).catch(function(){ //<-- Runs if the promise is rejected
});
关于javascript - 了解 Controller 和服务交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25496426/