J'essaye d'obtenir un .json
fichier du serveur Firebase distant.
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.
}
);
}
Mais si j'ouvre url
dans le navigateur, le fichier json se charge. Même si je wget url
le fichier json se charge. Mais par angulaire, il renvoie un 404
pas trouvé.
Maintenant le .json
le fichier distant a cette structure:
[
{
"hello":"Europe"
},
{
"hello":"USA"
}
]
Le fichier ci-dessus peut être récupéré en utilisant $ http.get () mais pas avec $ http.jsonp (). JSONP ne peut pas analyser le fichier .json avec la structure ci-dessus. Comment contourner cela?
Réponses:
1 pour la réponse № 1Vous devez spécifier un ?callback=JSON_CALLBACK
dans l'URL à laquelle vous passez $http.jsonp
.
De "Angulaire" $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.
Cette dernière ligne est ce qui vous manque.
Un exemple simple (en utilisant une base de données Firebase, pas un hébergement 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)
}
);
});
Au cas où vous voudriez le voir fonctionner: http://jsbin.com/robono/1/watch?js,console