0

我在这里关注 angular-poller 演示: https ://emmaguo.github.io/angular-poller/

我需要能够将参数传递到工厂以构造动态 url,以便使用 newTime arg 调用“greet”。

如何修改 poller.get() 以传入“newTime”?

poller1 = poller.get(greet, {action: 'jsonp_get', delay: 1000});

.factory('greet', function ($resource) {
    return $resource('https://www.example.com?time=' + newTime,
        {
        },
        {
            jsonp_get: { method: 'JSONP' }
        });
})

/ -- 演示 -- /

angular.module('myApp', ['ngResource', 'emguo.poller'])

  .factory('greet1', function ($resource) {
    return $resource('https://angularjs.org/greet.php',
      {
    callback: 'JSON_CALLBACK',
    name: 'Emma'
      },
      {
    jsonp_get: { method: 'JSONP' }
      });
  })

  .factory('greet2', function ($resource) {
    return $resource('https://angularjs.org/greet.php',
      {
    callback: 'JSON_CALLBACK',
    name: 'You'
      },
      {
    jsonp_get: { method: 'JSONP' }
      });
  })

  .controller('myController', function ($scope, poller, greet1, greet2) {
    var poller1, poller2;

    /*-- Automatically start poller1 on page load --*/
    poller1 = poller.get(greet1, {action: 'jsonp_get', delay: 1000});
    poller1.promise.then(null, null, function (data) {
      $scope.data1 = data;
    });

    /*-- Actions --*/
    $scope.stop = function () {
      poller1.stop();
    };

    $scope.restart = function () {
      poller1 = poller.get(greet1);
    };

    $scope.faster = function () {
      poller1 = poller.get(greet1, {delay: 300});
    };

    $scope.slower = function () {
      poller1 = poller.get(greet1, {delay: 1500});
    };

    $scope.startPoller2 = function () {
      poller2 = poller.get(greet2, {action: 'jsonp_get', delay: 1000});
      poller2.promise.then(null, null, function (data) {
    $scope.data2 = data;
      });
    };

    $scope.stopBoth = function () {
      poller.stopAll();
    };

    $scope.restartBoth = function () {
      poller.restartAll();
    };
  });
4

1 回答 1

0

没有使用angular-poller,但似乎您应该能够通过该属性获得所需的内容argumentsArray

var poller1 = poller.get(greet, {
    action: 'jsonp_get', 
    delay: 1000,
    argumentsArray: [{
        time: newTime
    }]
});

检索轮询器时会评估数组argumentsArray,即时间。


编辑:澄清后,您似乎需要为轮询的每个滴答声更改一个参数,而不是在您获得轮询器时。您可以通过在请求拦截器中添加参数来解决这个问题:

// define interceptor
app.factory('requestInterceptor', function() {
    return {
        'request': function(request) {
            // if needed, wrap the following in a condition
            request.params = request.params || {};
            request.params.time = moment();
            return request;
        }
    }
})

// register interceptor
app.config(function ($httpProvider) {
    $httpProvider.interceptors.push('requestInterceptor');
})
于 2015-10-10T22:22:06.457 回答