$http.post does not work on the first time

I am experiencing very strange issue when building ionic app. I am calling auth API from server and it work very well in browser with $ionic serve --lab. However, when I try to run on Android with $ionic run android --device, it is not working on the first launch. No POST request received at server side. But when I kill the app and re-launch from android, its working again. Here is some code I made:

I try to call the API from the ‘onEnter’ state:

  $stateProvider

    .state('splash', {
      url         : '/',
      templateUrl : 'templates/splash.html',
      onEnter     : function($state, $localStorage, $ionicLoading, $api) {
        // initialize app status from server
        $ionicLoading.show({
          template      :    '<ion-spinner icon="lines"></ion-spinner>',
          noBackdrop    :    true
        });

        $api.auth().then(function(res) {
            alert('success auth');
          }).catch(function(err) {
            alert('something wrong');
            console.log(err);
          });
      }
    })

and the service:

  api.auth = function() {
    var defer = $q.defer();

    //$http.get(SERVER.domain + SERVER.apiPath + 'api/auth')
    $http.post(SERVER.domain + SERVER.apiPath + 'api/auth', api.serialize({
      locale  : $localStorage.get('settings').locale,
      app_id  : SERVER.appId
    }))
    .success(function(data) {
      try
      {
        var res = angular.fromJson(data);
        if (res.status == 'Y')
        {
          defer.resolve(res);
        }
        else
        {
          defer.reject(res.msg);
        }
      }
      catch (err)
      {
        defer.reject(err);
      }
    })
    .error(function(err) {
      defer.reject(err);
    });

    return defer.promise;

  };

When I change to GET instead of POST from the service, its work on the device. However, the server API only accept POST request. can someone please let me know how to solve this issue? Thanks.

try adding $timeout.

$timeout(function(){ $http.post..... }, 1000);

Its still not calling the POST request after adding $timeout…

The issue is most likely that it hasn’t been initialized all the way. You need to figure out a way to make sure that ionic and that the pages are all completely loaded before it tries to call it. If you’re inspecting it in chrome or safari, you should see it attempt to make the request. It never hurts to try and wrap it in a try {} catch() {}