【问题标题】:Unable to pull data from JSON file in factory AngularJS无法从工厂AngularJS中的JSON文件中提取数据
【发布时间】:2016-02-01 14:30:28
【问题描述】:

我有一个以下格式的 Json 文件: json 文件的名称是 discover.json,路径是 json-files/discover.json

    {"data": [
{"username": "aky123", 
    "name": "ajay"}, 
    {"username": "sky123",
     "name": "sanjay"}
    ]}

我的工厂是:

var myAppServices=angular.module('myAppServices',['ngResource']);

myAppServices.factory('ProfileData',['$resource', function($resource){
    return $resource('/discover/:username.json', {}, {
        query: {method: 'GET' , params: {username: 'json-files/discover' }, isArray: true }
    });
}]);

App.js:

myApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/discover', {
        templateUrl: 'partials/home-page.html',
        controller: 'ProfileListCtrl'
      }).
      when('/discover/:username', {
        templateUrl: 'partials/profile-detail.html',
        controller: 'ProfileDetailCtrl'
      })

在控制器中:

myAppControllers.controller('ProfileListCtrl',['$scope', 'ProfileData', '$timeout', function($scope, ProfileData, $timeout) {
        $scope.profile=ProfileData.query();
    console.log($scope.profile);
}]);

$scope.profile 无法从 JSON 文件中提取数据,我无法理解我的错误,所以请帮助我..

【问题讨论】:

  • "json 文件名是discover.json" 如果文件名是discover.json 那你为什么用'/discover/:username.json'

标签: javascript angularjs json html


【解决方案1】:

你没有有效的 json

有效的 json 是:

 {
    "data": [{
        "username": "aky123",
        "name": "ajay"
    }, {
        "username": "sky123",
        "name": "sanjay"
    }]
}

【讨论】:

  • 此外,在调试任何返回 JSON 的内容时,请将您的 JSON 放入 jsonlint 以进行快速冒烟测试。
  • @Mike88 我更正了我的 Json 格式,但仍然无法提取数据。我认为 service.js 中有一些错误,如果你能在那部分帮助我,那就太好了。 :)
【解决方案2】:

此代码在我的本地主机中工作

//Service.js
myAppServices.factory('ProfileData',['$resource', function($resource){
return $resource('/discover/:username.json', {},{
'query': {method: 'GET',{}, isArray: false }
});
}]);
//Controller.js
var promise = ProfileData.query();
promise.$promise.then(function(response) {
$scope.data = response.data;
});
//view.html
<li ng-repeat="name in data">
    {{name.username}}
</li>      

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多