AngularJS:工厂 $http.get JSON 文件 [英] AngularJS: factory $http.get JSON file

查看:31
本文介绍了AngularJS:工厂 $http.get JSON 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望仅使用硬编码的 JSON 文件在本地进行开发.我的JSON文件如下(放入JSON验证器时有效):

I am looking to develop locally with just a hardcoded JSON file. My JSON file is as follows (valid when put into JSON validator):

{
    "contentItem": [
            {
            "contentID" : "1", 
            "contentVideo" : "file.mov",
            "contentThumbnail" : "url.jpg",
            "contentRating" : "5",
            "contentTitle" : "Guitar Lessons",
            "username" : "Username", 
            "realname" : "Real name",
            "contentTags" : [
                { "tag" : "Guitar"},
                { "tag" : "Intermediate"},
                { "tag" : "Chords"}
            ],      
            "contentAbout" : "Learn how to play guitar!",
            "contentTime" : [
                { "" : "", "" : "", "" : "", "" : ""},
                { "" : "", "" : "", "" : "", "" : ""}
            ],          
            "series" :[
                { "seriesVideo" : "file.mov", "seriesThumbnail" : "url.jpg", "seriesTime" : "time", "seriesNumber" : "1", "seriesTitle" : "How to Play Guitar" },
                { "videoFile" : "file.mov", "seriesThumbnail" : "url.jpg", "seriesTime" : "time", "seriesNumber" : "2", "seriesTitle" : "How to Play Guitar" }
            ]
        },{
            "contentID" : "2", 
            "contentVideo" : "file.mov",
            "contentThumbnail" : "url.jpg",
            "contentRating" : "5",
            "contentTitle" : "Guitar Lessons",
            "username" : "Username", 
            "realname" : "Real name",
            "contentTags" : [
                { "tag" : "Guitar"},
                { "tag" : "Intermediate"},
                { "tag" : "Chords"}
            ],      
            "contentAbout" : "Learn how to play guitar!",
            "contentTime" : [
                { "" : "", "" : "", "" : "", "" : ""},
                { "" : "", "" : "", "" : "", "" : ""}
            ],          
            "series" :[
                { "seriesVideo" : "file.mov", "seriesThumbnail" : "url.jpg", "seriesTime" : "time", "seriesNumber" : "1", "seriesTitle" : "How to Play Guitar" },
                { "videoFile" : "file.mov", "seriesThumbnail" : "url.jpg", "seriesTime" : "time", "seriesNumber" : "2", "seriesTitle" : "How to Play Guitar" }
            ]
        }
    ]
}

当 JSON 在工厂内部进行硬编码时,我的控制器、工厂和 html 都可以正常工作.但是,现在我已经用 $http.get 代码替换了 JSON,它不起作用.我见过很多不同的 $http 和 $resource 示例,但不知道该去哪里.我正在寻找最简单的解决方案.我只是想为 ng-repeat 和类似指令提取数据.

I've gotten my controller, factory, and html working when the JSON was hardcoded inside the factory. However, now that I've replaced the JSON with the $http.get code, it doesn't work. I've seen so many different examples of both $http and $resource but not sure where to go. I'm looking for the simplest solution. I'm just trying to pull data for ng-repeat and similar directives.

工厂:

theApp.factory('mainInfoFactory', function($http) { 
    var mainInfo = $http.get('content.json').success(function(response) {
        return response.data;
    });
    var factory = {}; // define factory object
    factory.getMainInfo = function() { // define method on factory object
        return mainInfo; // returning data that was pulled in $http call
    };
    return factory; // returning factory to make it ready to be pulled by the controller
});

感谢任何和所有帮助.谢谢!

Any and all help is appreciated. Thanks!

推荐答案

好的,以下是需要研究的事项列表:

Okay, here's a list of things to look into:

1) 如果您没有运行任何类型的网络服务器,而只是使用 file://index.html 进行测试,那么您可能会遇到同源策略问题.见:

1) If you're not running a webserver of any kind and just testing with file://index.html, then you're probably running into same-origin policy issues. See:

https://code.google.com/存档/p/browsersec/wikis/Part2.wiki#Same-origin_policy

许多浏览器不允许本地托管的文件访问其他本地托管的文件.Firefox 确实允许这样做,但前提是您正在加载的文件与 html 文件(或子文件夹)位于同一文件夹中.

Many browsers don't allow locally hosted files to access other locally hosted files. Firefox does allow it, but only if the file you're loading is contained in the same folder as the html file (or a subfolder).

2) $http.get() 返回的成功函数已经为你拆分了结果对象:

2) The success function returned from $http.get() already splits up the result object for you:

$http({method: 'GET', url: '/someUrl'}).success(function(data, status, headers, config) {

所以用 function(response) 调用成功并返回 response.data 是多余的.

So it's redundant to call success with function(response) and return response.data.

3) 成功函数不会返回你传递给它的函数的结果,所以这不会像你想象的那样做:

3) The success function does not return the result of the function you pass it, so this does not do what you think it does:

var mainInfo = $http.get('content.json').success(function(response) {
        return response.data;
    });

这更接近您的预期:

var mainInfo = null;
$http.get('content.json').success(function(data) {
    mainInfo = data;
});

4) 但是您真正想要做的是返回一个对象的引用,该对象的属性将在数据加载时填充,因此如下所示:

4) But what you really want to do is return a reference to an object with a property that will be populated when the data loads, so something like this:

theApp.factory('mainInfo', function($http) { 

    var obj = {content:null};

    $http.get('content.json').success(function(data) {
        // you can do some processing here
        obj.content = data;
    });    

    return obj;    
});

mainInfo.content 将从 null 开始,当数据加载时,它会指向它.

mainInfo.content will start off null, and when the data loads, it will point at it.

或者,您可以返回 $http.get 返回的实际承诺并使用它:

Alternatively you can return the actual promise the $http.get returns and use that:

theApp.factory('mainInfo', function($http) { 
    return $http.get('content.json');
});

然后您可以在控制器的计算中异步使用该值:

And then you can use the value asynchronously in calculations in a controller:

$scope.foo = "Hello World";
mainInfo.success(function(data) { 
    $scope.foo = "Hello "+data.contentItem[0].username;
});

这篇关于AngularJS:工厂 $http.get JSON 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆