Search code examples
javascriptjsonangularjsfirebase-hosting

Obtaining JSONP files from Firebase hosting through Angular


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?


Solution

  • 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