简体   繁体   English

通过Angular从Firebase托管获取JSONP文件

[英]Obtaining JSONP files from Firebase hosting through Angular

I am trying to obtain a .json file from remote firebase server. 我正在尝试从远程Firebase服务器获取.json文件。

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.
        }
    );
}

But If I open url in the browser the json file loads. 但是,如果我在浏览器中打开url ,则会加载json文件。 Even if I wget url the json file loads. 即使我wget url json文件加载。 But through angular it returns a 404 not found. 但是通过角度返回未找到的404

Now the .json remote file has this structure: 现在, .json远程文件具有以下结构:

[
  { 
    "hello":"Europe"
  },

  {
    "hello":"USA"
  }
]

The above file can be fetched using $http.get() but not with $http.jsonp(). 可以使用$ http.get()而不是$ http.jsonp()来获取上述文件。 JSONP cant parse .json file with the above structure. JSONP无法解析具有上述结构的.json文件。 How can I work around this? 我该如何解决?

You need to specify a ?callback=JSON_CALLBACK in the URL that you pass to $http.jsonp . 您需要在传递给$http.jsonp的URL中指定?callback=JSON_CALLBACK $http.jsonp

From Angular's $http.jsonp documentation : 来自Angular的$http.jsonp文档

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.

That last line is what you're missing. 最后一行是您所缺少的。

A simple example (using a Firebase database, not Firebase hosting): 一个简单的示例(使用Firebase数据库,而不是Firebase托管):

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)
    }
  );  
});

In case you want to see it working: http://jsbin.com/robono/1/watch?js,console 如果您希望看到它正常工作: http : //jsbin.com/robono/1/watch?js,console

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM