Hitu Bansal
Hitu Bansal

Reputation: 3137

How to run http call as background in ionic Framework?

I am using ionic Framework. i have multiple HTTP service which is working fine. Now problem is that whenever i get response of any http call. i can't proceed further.

Can we run HTTP Service as a background process. So my application continues works without waiting for result.

here is my code

articleService.getArticles().then(function() {

    },function(err){

    });

and sercvice code

$http({
                url: "http://myservice.com",
                data: { user_id: 1 },
                method: 'POST',
                withCredentials: true,
            }).success(function (data) {
                deferred.resolve(data);
            }).error(function (err) {
             deferred.resolve(0);
            })
            return deferred.promise;
        }

Any idea? I need a solution in ionic framework which will work both for ios and andriod?

Thanks

Upvotes: 4

Views: 2787

Answers (3)

Marcel Schulze
Marcel Schulze

Reputation: 35

Maybe i misunderstand your question but i think your service code is wrong.

Try something like this

myApp.factory('articleService', function($http) {
    return {
        getArticles: function getArticles() {
              return $http({...}); // $http returns a promise, so you dont need your own defer.promise
        }
    }
});


//usage
//first: send or get data async
articleService.getArticles().then(function(resp){
    alert('called second');
    ...
});
// second: do something else, this will not wait for your response
alert('called first');

Upvotes: 0

Atul Chaudhary
Atul Chaudhary

Reputation: 3736

Look at this plunker this what you need and it is all angularjs so will work with ionic.

var app = angular.module('angularjs-starter', []);

app.config(function($routeProvider) {
    $routeProvider.
      when('/', {controller:'StartCtrl', templateUrl:'start.html'}).
      when('/main', {controller:'MainCtrl', templateUrl:'main.html'}).
      otherwise({redirectTo:'/'});
});

app.controller('MainCtrl', function($scope, Poller) {
  $scope.name = 'World';
  $scope.data = Poller.data;
});
app.controller('StartCtrl',function(){});
app.run(function(Poller) {});

app.factory('Poller', function($http, $timeout) {
  var data = { response: {}, calls: 0 };
  var poller = function() {
    $http.get('data.json').then(function(r) {
      data.response = r.data;
      data.calls++;
      $timeout(poller, 1000);
    });

  };
  poller();

  return {
    data: data
  };
});

Upvotes: 1

mohamed ayed
mohamed ayed

Reputation: 658

try to use html5 web workers what u need to do is multithreading and because that javascript is single threading environment you have to web workers

https://html.spec.whatwg.org/multipage/workers.html

Upvotes: 1

Related Questions