angular ionic $ http服务无法正常工作

时间:2015-07-16 13:40:36

标签: angularjs ionic

使用$ http加载json并不起作用。无法找出问题所在

.factory('streamStore', function ($http) {
    var cachedData = null;

    return {
        findAll: function getAll() {
            $http.get('img/sample.json').
                success(function (data, status, headers, config) {
                    console.log("inside stream controller");
                    cachedData = data; return cachedData;
                }).
                error(function (data, status, headers, config) {
                    // log error
                });
        }

在我的控制器中,我就是这样称呼的:

.controller('streamCtrl', function ($scope, ,streamStore) {
    $scope.streams = streamStore.findAll();//not working ,

2 个答案:

答案 0 :(得分:1)

您的代码中存在错误。请查看以下

.factory('streamStore', function ($http) {

 var cachedData = null;

 return {
    findAll: function() {
        $http.get('img/sample.json').
            success(function (data, status, headers, config) {
                console.log("inside stream controller");
                cachedData = data;
                return cachedData;
            }).
            error(function (data, status, headers, config) {
                // log error
            });
    }

然后打电话,就像你在控制器中打电话一样。

或使用此

.factory('streamStore', function ($http) {

 var cachedData = function(){
     return $http.get('img/sample.json');
 };

 return {
    findAll: function(){
        return cachedData();
       }
    }

});

然后在控制器

streamStore.findAll().then(function(response){
     console.log(response) // here is your data
})

答案 1 :(得分:1)

因为你没有从工厂退回任何东西。

.factory('streamStore', function ($http) {
    var cachedData = null;

    return {
        findAll: function getAll() {
            $http.get('img/sample.json').
                success(function (data, status, headers, config) {
                    console.log("inside stream controller");
                    cachedData = data; return cachedData;

                     // should return something 
                     return cachedData
                }).
                error(function (data, status, headers, config) {
                    // log error
                });
        }

另一个建议是让它变得安全。

return $http.get('img/sample.json')...

并在then中处理controller

.controller('streamCtrl', function ($scope, ,streamStore) {
   streamStore.findAll().then(function(res){
         //res will contain your data 
         $scope.streams =  res.data;
     });