我有一个工厂返回一个调用包含 JSON 的内部资源的对象:
.factory('cardFactory', function ($q, $http) {
return {
getOtherStuff: function () {
var deferred = $q.defer(),
httpPromise = $http.get('/static/cards.json');
httpPromise.then(function (response) {
deferred.resolve(response);
}, function (error) {
console.error(error);
});
return deferred.promise;
}
};
});
在我的 Controller 中我这样调用它:
var cardSuccess = function(data, status, headers, config) {
$scope.cards = data.data;
};
cardFactory.getOtherStuff()
.then(cardSuccess, cardError);
在浏览器中 $scope.cards 已填充但在设备上未填充。
有什么想法吗?
最佳答案
嗯..,不确定。
我在我的 Ionic 应用程序中以不同的方式使用它,效果很好。
.factory('cardFactory', function ( $http ) {
var promise;
var cards = {
getOtherStuff: function() {
if ( !promise ) {
// $http returns a promise, which has a then function, which also returns a promise
promise = $http.get( '/static/cards.json' ).then(function (response) {
// The then function here is an opportunity to modify the response
// The return value gets picked up by the then in the controller.
return response.data;
});
}
return promise; // Return the promise to the controller
}
};
return cards;
})
然后,在 Controller 上,调用它:
$scope.getData = function() {
// Call the async method and then do stuff with what is returned inside our own then function
cardFactory.getOtherStuff().then(function(d) {
$scope.cards= d;
});
}
$scope.getData();
希望对您有所帮助。
[编辑:] 可能是 $http.get url,是相对的?您是否尝试过使用绝对 URL?
关于javascript - Angular $http get 在浏览器中有效,但在设备上无效 - Ionic,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25686917/