【问题标题】:error when reading json file using angular resource使用角度资源读取 json 文件时出错
【发布时间】:2014-09-26 05:58:33
【问题描述】:

我正在尝试使用 Angular ngResource 模块从 json 文件中获取数据,但我在控制台上收到错误 404 - URL 正在与调用 get 函数后的代码连接。

这是错误:

localhost 前缀/test_data/data.json/function%20(data)%20%7B%20%20%20%20%20%20%20%20%20%20%20%20console.log(data );%20%20%20%20%20%20%20%20%7D

这是我正在使用的代码:

json 服务 -

angular.module('jsonServices',['ngResource']).factory('JsonService', 
    function ($resource) { 
    return $resource('/test_data/data.json'); 
});

使用服务的控制器:

angular.module('myApp.controllers')
.controller('mainController', function ($scope, JsonService) {
        JsonService.get(function (data) {
            console.log(data);
        });
});

启动这一切的应用程序 js:

angular.module('myApp',['myApp.controllers','jsonServices','ui.router'])
.config(function($stateProvider, $urlRouterProvider){
    $stateProvider.state('home',{
        url:'/home',
        template:'some template path goes here',
        controller:'mainController'
    };
});

如您所见,“函数(数据)”作为字符串添加到 url。还有一件事是当我尝试访问 json 文件浏览到它的位置时,我可以看到 json 文件的内容 OK。

有没有人遇到过这个问题并找到解决方法?我在这里做错了什么或遗漏了什么?

谢谢,

伊兰

【问题讨论】:

  • 你用的是哪个版本的angularjs?
  • 我已将您的代码放入 plunker,它似乎工作正常:plnkr.co/edit/aCxGngQyEbNBfxCBtUiG?p=preview
  • 我知道在 plunker 中它可以工作,但在我的开发机器上 - 使用节点 js 静态服务器和 chrome 它会出现此错误。我认为这与我没有使用 html5mode(true) 的事实有关——现在当我切换到它时,它进入了无限循环——但我希望很快解决另一个问题。
  • 那时我不知道。顺便说一句,如果您将呼叫更改为 JsonService.get({}, function (data) { 会发生什么?
  • 似乎第一个参数总是被确定为params,这很奇怪。尝试在angular-resource.js#L470 设置断点,看看会发生什么。

标签: javascript json angularjs file ngresource


【解决方案1】:

发现问题了,好像我用了bower包调用ng-resource而不是angular-resource。

【讨论】:

    猜你喜欢
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2018-09-10
    • 2020-10-11
    相关资源
    最近更新 更多