我在我的服务中设置了一个条件,以便每次只调用该数据。但我在回调中得到的数据是在数组中,我希望它在对象中。那么它如何将它作为回调中的对象并将其发送给控制器。
var _getSettings = function (callback) {
$http.get('localhost:8081/app/getSettings')
.success(function (data,response) {
if (data.length>0) {
callback(data);
}
}).error(function (data,error) {
if (callback) {
callback(null, data);
}
});
答案 0 :(得分:1)
返回$http
承诺并在您的控制器上处理:
服务:
var _getSettings = function () {
return $http.get('localhost:8081/app/getSettings');
}
控制器:
_getSettings()
.success(function(data, response) {
if (data.length > 0) {
callback(data[0]); // return data[0]
}
})
.error(function(data, error) {
if (callback) {
callback(null, data);
}
});
答案 1 :(得分:0)
尝试以下代码
var _getSettings = function (callback) {
$http.get('localhost:8081/app/getSettings')
.success(function (data,response) {
var obj = JSON.parse(data);
if (obj.length>0) {
callback(obj);
}
}).error(function (data,error) {
if (callback) {
callback(null, data);
}
});
答案 2 :(得分:0)
将函数调用部件处理到控制器本身。只需通过服务self.view.addConstraint(NSLayoutConstraint(item: customNavBar, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: customNavBar, attribute: .Right, relatedBy: .Equal, toItem: self.view, attribute: .Right, multiplier: 1.0, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: customNavBar, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1.0, constant: 0))
bdNavBar.addConstraint(NSLayoutConstraint(item: customNavBar, attribute: NSLayoutAttribute.Height, relatedBy: .Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 50))
self.tabBar.bringSubviewToFront(customNavBar)
从控制器中的API获取承诺。
服务:
httpCall
控制器:
在控制器中注入app.service('httpCall', [
'$http',
'$q',
'storageService',
'$location',
function(
$http,
$q,
storageService,
$location
) {
this.callAPI = function() {
var deferred = $q.defer();
var url = 'localhost:8081/app/getSettings';
var method = 'GET';
var params = {};
var data = {};
$http({
url: url,
method: method,
params: params,
data: data
})
.then(function successCallback(response) {
deferred.resolve(response);
}, function errorCallback(response) {
deferred.reject(response);
});
return deferred.promise;
};
}
]);
。
httpCall