Obtaining JSONP files from Firebase hosting through Angular

我怕爱的太早我们不能终老 提交于 2019-11-28 06:12:36

问题


I am trying to obtain a .json file from remote firebase server.

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. Even if I wget url the json file loads. But through angular it returns a 404 not found.

Now the .json remote file has this structure:

[
  { 
    "hello":"Europe"
  },

  {
    "hello":"USA"
  }
]

The above file can be fetched using $http.get() but not with $http.jsonp(). JSONP cant parse .json file with the above structure. How can I work around this?


回答1:


You need to specify a ?callback=JSON_CALLBACK in the URL that you pass to $http.jsonp.

From 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.

That last line is what you're missing.

A simple example (using a Firebase database, not Firebase hosting):

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



来源:https://stackoverflow.com/questions/25564200/obtaining-jsonp-files-from-firebase-hosting-through-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!