简体   繁体   English

Angular JS资源调用以获取数组中的JSON数据

[英]Angular js resource call to get json data in array

Created factory that will return json data and calling it from controller, but it is coming empty. 创建了将返回json数据并从控制器调用它的工厂,但是它为空。 don't know where I made mistake. 不知道我在哪里犯错。 no console error and in network json is also loading. 没有控制台错误,并且网络 json也正在加载。

    'use strict';
var app = angular.module('angularJson', ['ngResource']);

    app.factory('loadJsonService', ['$resource', function ($resource) {
        return {
            getData: function () {
                return $resource('json/productDetails.json');
            }
        };
    }])

  app.controller('angularJsonCtrl',['$scope', 'loadJsonService',function($scope, loadJsonService){

    $scope.loadProducts = function(noOfData){
        $scope.productDetails = [];
        $scope.productDetails = loadJsonService.getData().query();
    }

  }]);

You have to put wait till request gets completed & there after you need to use .$promise.then over $resource.query function call. 您需要等到请求完成后再使用.$promise.then ,然后再进行$resource.query函数调用。 So that you could put function which will get call on success of API call. 这样您就可以放置将在API调用成功时得到调用的函数。

loadJsonService.getData().query().$promise.then(function(res){ //success function
   $scope.productDetails = res;
}, function(error){ //error function
   console.log(error);
})

You must in getData function set $http request like this 您必须在getData函数中设置$ http这样的请求

$http.jsonp("json/productDetails.json")
        .success(function(response) {
          callback(response);
        });

Try built in query method. 尝试内置query方法。 If you want to write your own get method do the following, 如果您要编写自己的get方法,请执行以下操作:

{
   method: 'GET',
   params: {
   key: value
},
isArray: true,
cache: true // if you want to cache
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM