如何使用$ resource从本地json文件中获取数据

时间:2016-10-04 12:36:33

标签: angularjs angular-resource

我正在尝试多种方法来访问本地json文件中的用户,以便稍后将它们与用户输入进行比较。如果匹配,则允许访问,但我现在的主要问题是访问这些用户。   到目前为止我的代码:

entire code

json file

我做错了什么?我是编程方面的新手。我一直在尝试不同的事情,没有任何作用。 非常感谢你的帮助

3 个答案:

答案 0 :(得分:3)

您可以通过浏览器访问该文件(通过您的网址localhost:8080 / resources / data / users.json)吗?

如果你不能,你将无法通过$ resource或$ http访问。

如果可以,任何方法都应该有效:

1)通过$resource

$scope.users = [];

var UsersResource = $resource('/resources/data/users.json');

我们可以通过回调获得响应

UsersResource.get({}, function(response) {
    $scope.users = response;
});

或$ promise

UsersResource.get().$promise.then(function(response) {
    $scope.users = response;
});

2)通过$http.get

$scope.users = [];

$http.get('/resources/data/users.json').then(function(response) {
    $scope.users = response;
});

在您的示例中,您正在尝试通过返回$ resource获取用户数组,但$ resource返回带有方法的对象。每个方法都有回调(成功,错误)或返回$ promise对象。

答案 1 :(得分:0)

如果您要获取json文件,则无需使用$resource。请改用$http

this.getUsers = function(){
  return $http.get('path/to/file.json');
};

用法:

dataService.getUsers().then(function(resp){
    //Do something with the data
    $scope.users = resp;
})

$resource用于与RESTful apis通信时使用。您getUsers()正在做的事实上是返回一个资源对象,然后您可以在其上调用get()。但我建议在这种情况下使用$http

答案 2 :(得分:0)

如果你想使用$ resouce,你需要在你的控制器/工厂中创建两个函数,其中“templatesSuccess”返回请求数据。

        getAllTemplates: function(query) {
            return $resource(CONST.CONFIG.BASE_URL + 'receiver/get-templates').get(query, obj.templatesSuccess).$promise;
        },


        templatesSuccess: function(response) {
            obj.allTemplates = response;
        },