linluk linluk - 4 months ago 14
AngularJS Question

Loading JSON via $http. Works in Browser but not on Android (Device or Emulator)

I just started learning ionic framework and angular js to develop an android app. I wanted to write APOD viewer (=Astronomy Picture of the Day).

I do an api call to: https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&hd=true

wich returns a JSON string. then i view the picture (from the "hdurl" field).

everything works as expected when i try it in my browser. but when i build the app and run it in the emulator or on my phone it seems like i dont get an answer to my $http() call.

here is my code:

$scope.apodImgUrl = "img/loading.gif";
$scope.apiUrl = "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&hd=true";
$http({
method: "GET",
url: $scope.apiUrl
}).then(function (response){
if(response == null) {
showError($location, "No Data", "Received nothing!");
}else{
if(response.data.media_type == "image") {
$scope.apodImgUrl = response.data.hdurl;
}else{
showError($location, "No Image", "Only Images are Supported (so far!)");
}
}
},function (errorResponse) {
showError($location, "HTTP GET Error", errorResponse);
});


I don't get an error neigther the image. it just shows me my loading.gif.

I have allready used the cordova whitelist plugin and added:

<access origin="*" subdomains="true"/>
<allow-navigation href="*" />
<allow-intent href="*" />


to my config.xml.

I also have tried to add a proxy to my ionic.project file:

"proxies": [
{
"path": "/planetary/apod",
"proxyUrl": "https://api.nasa.gov/planetary/apod"
}
]


I have also tried lots of different combinations how to call $http. (f.e.
$http.get().success().error()
or
$http.get().then()
or the plain
$http()
). with the same result.

any Ideas? Thanks.

Answer

Please add whitelist plugin in your project.

cordova plugin add cordova-plugin-whitelist --save

That will enable http request in your android device. And also check your android AndroidManifest.xml.It needs this permission

<uses-permission android:name="android.permission.INTERNET" />

at the last add these lines in your config.xml

<access origin="*"/>
<allow-intent href="*"/>
<allow-navigation href="*"/>

Then your http request will work correctly thanks.