首先,我有这样的工厂:
app.factory('getApiUrl', function (httpq, $q) {
var obj = {};
obj.getResponse = function (hurl) {
var promise = $q.defer();
httpq.get(hurl).then(function (data) {
//obj = data.data;
promise.resolve(data.data);
})
return promise.promise;
}
return obj;
});
然后我创建控制器并像这样调用工厂:
app.controller('mainController', function ($scope, httpq, $q, getApiUrl) {
$scope.message = "Main Content";
var namees = new Array();
var testc = getApiUrl.getResponse(hurl);
$scope.names = testc.data;
});
但它没有用。
答案 0 :(得分:2)
getResponse
方法返回promise object。您需要为响应何时解决提供回调。那么正确的用法是:
app.controller('mainController', function ($scope, httpq, $q, getApiUrl) {
$scope.message = "Main Content";
var namees = new Array();
getApiUrl.getResponse(hurl).then(function(data) {
var testc = data;
$scope.names = testc.data;
});
});
作为旁注,您还应该摆脱服务中的多余$q.defer
,因为httpq.get(hurl)
已经是一个承诺:
obj.getResponse = function (hurl) {
return httpq.get(hurl).then(function (data) {
return data.data;
});
}