AngularJS:工厂$ http.get JSON文件

jst*_*cks 84 json factory http angularjs

我期待在本地开发只有一个硬编码的JSON文件.我的JSON文件如下(放入JSON验证器时有效):

{
    "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" }
            ]
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

当JSON在工厂内硬编码时,我已经得到了我的控制器,工厂和html工作.但是,现在我已经用$ http.get代码替换了JSON,它不起作用.我已经看到了很多不同的$ http和$资源的例子,但不知道该去哪里.我正在寻找最简单的解决方案.我只是想为ng-repeat和类似的指令提取数据.

厂:

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
});
Run Code Online (Sandbox Code Playgroud)

任何和所有的帮助表示赞赏.谢谢!

Kar*_*les 218

好的,这是一个要查看的事项列表:

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

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

许多浏览器不允许本地托管文件访问其他本地托管文件.Firefox确实允许它,但前提是您加载的文件包含在与html文件(或子文件夹)相同的文件夹中.

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

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

因此,使用函数(响应)调用成功并返回response.data是多余的.

3)成功函数不会返回您传递的函数的结果,因此这不符合您的想法:

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

这更接近你的意图:

var mainInfo = null;
$http.get('content.json').success(function(data) {
    mainInfo = data;
});
Run Code Online (Sandbox Code Playgroud)

4)但你真正想要做的是返回一个对象的引用,该对象具有一个将在数据加载时填充的属性,所以像这样:

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;    
});
Run Code Online (Sandbox Code Playgroud)

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

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

theApp.factory('mainInfo', function($http) { 
    return $http.get('content.json');
});
Run Code Online (Sandbox Code Playgroud)

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

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

  • 嘿,这是一个回应和角度$ http课程相同的价格 - 很好的答案! (27认同)
  • 在4)的解释中,在解决$ http.get()之前,不会调用'return obj'吗?只是问,因为我认为这就是发生在我身上的事情. (4认同)
  • 是的,它会的.但是当$ http.get()被解析时调用的闭包保持对'obj'的引用.它将填写您可以使用的内容属性. (3认同)

Qia*_*ang 21

我想说明接受答案第四部分是错误的 .

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;    
});
Run Code Online (Sandbox Code Playgroud)

上面的代码@Karl Zilles写的将会失败,因为obj它总是会在收到数据之前返回(因此值总是会null),这是因为我们正在制作一个异步调用.

本文将讨论类似问题的详细信息


在Angular中,使用 $promise当您想要进行异步调用时处理获取的数据.

最简单的版本是

theApp.factory('mainInfo', function($http) { 
    return {
        get:  function(){
            $http.get('content.json'); // this will return a promise to controller
        }
});


// and in controller

mainInfo.get().then(function(response) { 
    $scope.foo = response.data.contentItem;
});
Run Code Online (Sandbox Code Playgroud)

我不使用的原因successerror是我刚刚从发现的文档,这两种方法已被弃用.

$http遗产的承诺方法成功和错误已被弃用.请改用标准then方法.

  • 在工厂中使用``return $ http.get('content.json');``,否则返回null. (2认同)
  • 嘿,只是一个抬头.它起作用的原因(与你的答案相反)是你返回对象的引用.成功函数还引用了同一个对象.当ajax函数最终返回时,它会更新返回的原始对象中的"content"属性.试试吧.:-) (2认同)