2014-08-29 37 views
1

我试图从远程Firebase服务器获取.json文件。通过Angular获取Firebase托管的JSONP文件

function fetchData(remoteJsonId){ 
    var url = "https://myAppName.firebaseapp.com/topics/"+remoteJsonID; 
    console.log(url); //This variable expands to the full domain name which is valid and      returns success both on wget and the browser 
    $http.jsonp(url).then(
     function(resp){ 

     }, 
     function(err){ 
      console.log(err.status) // This posts "404" on console. 
     } 
    ); 
} 

但是如果我在浏览器中打开url加载json文件。即使我加载了json文件。但通过角度,它返回一个404找不到。

现在.json远程文件具有这种结构:

[ 
    { 
    "hello":"Europe" 
    }, 

    { 
    "hello":"USA" 
    } 
] 

上述文件可以使用$ http.get(),但不与$ http.jsonp被获取()。 JSONP无法解析具有上述结构的.json文件。我该如何解决这个问题?

+1

尝试'$ http.jsonp(的“http:// myFireBaseApp.com/MyFolder/JSONFile')。然后' – 2014-08-29 08:35:42

+0

请查看更新后的链接。 – InfinitePrime 2014-08-29 12:23:56

+0

您修改删除了链接。您能否提供一个真正的链接(如果您觉得需要,只需将Firebase的名称删除)?你可以检查浏览器的控制台,看看它最终调用哪个URL吗? – 2014-08-29 14:15:00

回答

1

您需要在传递给$http.jsonp的URL中指定?callback=JSON_CALLBACK

Angular's $http.jsonp documentation

jsonp(url, [config]); 
Shortcut method to perform JSONP request. 

Parameters 
Param Type Details 
url  string 
Relative or absolute URL specifying the destination of the request. 
The name of the callback should be the string JSON_CALLBACK. 

最后一行是你错过了什么。

一个简单的例子(使用火力地堡数据库,而不是火力地堡主办):

var app = angular.module('myapp', []); 
app.controller('mycontroller', function($scope, $http) { 
    var url = 'https://yourfirebase.firebaseio.com/25564200.json'; 
    $http.jsonp(url+'?callback=JSON_CALLBACK').then(
    function(resp){ 
     console.log(resp.data); // your object is in resp.data 
    }, 
    function(err){ 
     console.error(err.status) 
    } 
); 
}); 

如果你想看到它的工作:http://jsbin.com/robono/1/watch?js,console

+0

它仍然返回404.究竟发生了什么? – InfinitePrime 2014-08-30 05:52:49

+0

您通过jsbin提供的关于Firebase作品的链接。但为什么不是我的?在Firebase上托管JSON文件需要一些独特的设置。 – InfinitePrime 2014-08-30 09:40:54

+0

你没有分享你的'remoteJsonId',所以我不能确定。但我高度怀疑你只是忘了在URL的末尾添加'?callback = JSON_CALLBACK',这就是我答案的第一行。除了使代码工作的最低限度,我什么也没做。如果这不能解决你的问题,我建议你设置一个可以复制你的问题的小提琴/箱子。 – 2014-08-30 13:07:37