AngularJS将变量传递给使用$ http + $ interval的服务

时间:2014-09-12 19:44:41

标签: javascript ajax json angularjs

在与$http$interval争吵时找到此代码。

http://embed.plnkr.co/fSIm8B/script.js

分叉到: http://plnkr.co/edit/Al8veEgvESYA0rhKLn1q

为了使它有用,我如何将变量传递给服务?

显示意图的代码损坏:

var myAppModule = angular.module("myApp", ['ngMockE2E']);

myAppModule.controller('MyController', function($scope, pollingService) {

var stopNow = 5;
var id = 1001;

pollingService(stopNow, id).then(
function(value) {
  //fully resolved (successCallback)
  $scope.data = value;
  console.log('Success Called!');
},
function(reason) {
  //error (errorCallback)
  console.log('Error:' + reason);
},
function(value) {
  //notify (notifyCallback)
  $scope.data = value;
  console.log('Notify Calls:' + value.count);
}
);

});

myAppModule.factory("pollingService", function ($http, $interval, $q, $httpBackend) {

var data = { resp: {}, status: 'Initialized', count: 0};
var deferred = $q.defer();

$httpBackend.whenGET("data.json").respond({type:'mock'});

//just loop 10 times for an example
var completed = $interval(function(ip) {
data.status = 'Running';

**//How can I Change the $http URL by passing a variable in?**
$http.get('/getId/' + id).then(function(r) {
  data.resp = r.data.type;
  data.count++;
  **//Instead of 5 I want to pass this in as an variable**
  if (data.count==stopNow)
  {
    $interval.cancel(completed);
  }
  console.log('Http\'s:' + data.count);
  deferred.notify(data);
});
}, 500, 10);

completed.then(function(){
data.status = 'Completed!';
deferred.resolve(data); 
});

return deferred.promise;
});

1 个答案:

答案 0 :(得分:1)

您可以在服务中返回一项功能:

myAppModule.factory("pollingService", function ($http, $interval, $q, $httpBackend) {

return {
      doSomething: function(arg1, arg2){
        // Your code goes here
        return deferred.promise;
     }
}

然后在控制器上

pollingService.doSomething(arg1,arg2).then(...)