2014-09-12 77 views
0

在与$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

你可以在你的服务回报功能:

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(...) 
+0

非常感谢您的! http://plnkr.co/edit/Al8veEgvESYA0rhKLn1q – 2014-09-12 21:04:23