gpt4 book ai didi

javascript - AngularJS 将变量传递到使用 $http + $interval 的服务中

转载 作者:行者123 更新时间:2023-12-03 11:51:30 25 4
gpt4 key购买 nike

在与 $http$interval 斗争时发现了这段代码。

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

将其 fork 到: 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;
});

最佳答案

您可以在服务中返回一个函数:

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

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

然后在 Controller 上

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

关于javascript - AngularJS 将变量传递到使用 $http + $interval 的服务中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25815712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com