【问题标题】:AngularJS pass a variable into service that use $http + $intervalAngularJS 将一个变量传递给使用 $http + $interval 的服务
【发布时间】:2014-09-12 19:44:40
【问题描述】:

在处理$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;
});

【问题讨论】:

    标签: javascript ajax json angularjs


    【解决方案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(...)
    

    【讨论】:

      猜你喜欢
      • 2014-09-28
      • 2014-05-09
      • 1970-01-01
      • 2013-08-08
      • 1970-01-01
      • 1970-01-01
      • 2020-02-24
      • 2021-08-05
      • 2021-04-01
      相关资源
      最近更新 更多