Giter VIP home page Giter VIP logo

angular-poller's Introduction

Angular Poller

Build Status Coverage Status devDependency Status npm version

Lightweight AngularJS poller service which can be easily injected into controllers. It uses a timer and sends requests every few seconds to keep the client synced with the server. Angular Poller supports $resource, $http and Restangular.

Demo: http://emmaguo.github.io/angular-poller/

Table of contents

Install

You can install this package either with npm or with bower.

npm

npm install angular-poller

Then add emguo.poller as a dependency for your app:

angular.module('myApp', [require('angular-poller')]);

bower

bower install angular-poller

Add a <script> to your index.html:

<script src="/bower_components/angular-poller/angular-poller.js"></script>

Then add emguo.poller as a dependency for your app:

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

cdnjs

You can also use cdnjs files:

<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-poller/0.4.5/angular-poller.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-poller/0.4.5/angular-poller.min.js"></script>

Quick configuration

myModule.controller('myController', function($scope, $resource, poller) {

    // Define your resource object.
    var myResource = $resource(url[, paramDefaults]);

    // Get poller. This also starts/restarts poller.
    var myPoller = poller.get(myResource);

    // Update view. Since a promise can only be resolved or rejected once but we want
    // to keep track of all requests, poller service uses the notifyCallback. By default
    // poller only gets notified of success responses.
    myPoller.promise.then(null, null, callback);

    // Stop poller.
    myPoller.stop();

    // Restart poller.
    myPoller.restart();

    // Remove poller.
    myPoller.remove();
});

Advanced usage

Customize $resource poller

myModule.controller('myController', function($scope, $resource, poller) {

    // Define your resource object.
    var myResource = $resource(url[, paramDefaults], {
        myQuery: {
            method: 'GET',
            isArray: true,
            headers: ...
        },
        ...
    });

    // Get poller.
    var myPoller = poller.get(myResource, {
        action: 'myQuery',
        delay: 6000,
        argumentsArray: [
            {
                verb: 'greet',
                salutation: 'Hello'
            }
        ]
    });

    myPoller.promise.then(null, null, callback);
});

Similar to how you invoke action methods on the class object or instance object directly ($resource), the format of argumentsArray is:

  • HTTP GET "class" actions: [parameters]
  • non-GET "class" actions: [parameters], postData
  • non-GET instance actions: [parameters]

Customize $http poller

myModule.controller('myController', function($scope, poller) {

    // Get poller.
    var myPoller = poller.get('api/test/123', {
        action: 'jsonp',
        delay: 6000,
        argumentsArray: [
            {
                params: {
                    param1: 1,
                    param2: 2
                },
                headers: {
                    header1: 1
                }
            }
        ]
    });

    myPoller.promise.then(null, null, callback);
});

The format of argumentsArray is:

  • GET, DELETE, HEAD and JSONP requests: [config]
  • POST, PUT, PATCH requests: data, [config]

config is the object describing the request to be made and how it should be processed. It may contain params, headers, xsrfHeaderName etc. Please see $http documentation for more information.

Customize Restangular poller

myModule.controller('myController', function($scope, Restangular, poller) {

    // Get poller.
    var myPoller = poller.get(Restangular.one('test', 123), {
        action: 'get',
        delay: 6000,
        argumentsArray: [
            {
                param1: 1,
                param2: 2
            },
            {
                header1: 1
            }
        ]
    });

    myPoller.promise.then(null, null, callback);
});

Angular Poller supports all Restangular action methods. Here argumentsArray is exactly the same as the input arguments for the original method function. For instance the argumentsArray for element method getList(subElement, [queryParams, headers]) would be subElement, [queryParams, headers], and the argumentsArray for collection method getList([queryParams, headers]) would be [queryParams, headers], etc.

Update argumentsArray while poller is running

To update argumentsArray without restarting poller, you can pass in argumentsArray as a function, which gets evaluated on every tick.

var myPoller = poller.get(myResource, {
    action: 'get',
    delay: 6000,
    argumentsArray: function() {
        return [
            {
                param1: $scope.param1,
                param2: $scope.param2
            },
            {
                header1: 1
            }
        ]
    }
});

myPoller.promise.then(null, null, callback);

Error handling

One way to capture error responses is to use the catchError option. It indicates whether poller should get notified of error responses.

var myPoller = poller.get(myTarget, {
    catchError: true
});

myPoller.promise.then(null, null, function(result) {

    // If catchError is set to true, this notifyCallback can contain either
    // a success or an error response.
    if (result.$resolved) {

        // Success handler ...
    } else {

        // Error handler: (data, status, headers, config)
        if (result.status === 503) {
            // Stop poller or provide visual feedback to the user etc
            poller.stopAll();
        }
    }
});

Alternatively you can use AngularJS interceptors for global error handling like so:

myModule.config(function($httpProvider) {
    $httpProvider.interceptors.push(function($q, poller) {
        return {
            'responseError': function(rejection) {
                if (rejection.status === 503) {
                    // Stop poller or provide visual feedback to the user etc
                    poller.stopAll();
                }
                return $q.reject(rejection);
            }
        };
    });
});

You may also use setErrorInterceptor if you are using Restangular.

Multiple pollers

myModule.controller('myController', function($scope, poller) {

    var poller1 = poller.get(target1),
        poller2 = poller.get(target2);

    poller1.promise.then(null, null, callback);
    poller2.promise.then(null, null, callback);

    // Total number of pollers
    console.log(poller.size());

    // Stop all pollers.
    poller.stopAll();

    // Restart all pollers.
    poller.restartAll();

    // Stop and remove all pollers.
    poller.reset();
});

Multiple controllers

myModule.factory('myTarget', function() {
    // return $resource object, Restangular object or $http url.
    return ...;
});

myModule.controller('controller1', function($scope, poller, myTarget) {
    // Register and start poller.
    var myPoller = poller.get(myTarget);
    myPoller.promise.then(null, null, callback);
});

myModule.controller('controller2', function($scope, poller, myTarget) {
    // Get existing poller and restart it.
    var myPoller = poller.get(myTarget);
    myPoller.promise.then(null, null, callback);
});

myModule.controller('controller3', function($scope, poller, myTarget) {
    poller.get(myTarget).stop();
});

Only send new request if the previous one is resolved

Use the smart option to make sure poller only sends new request after the previous one is resolved. It is set to false by default.

var myPoller = poller.get(myTarget, {
    action: 'query',
    delay: 6000,
    argumentsArray: [
        {
            verb: 'greet',
            salutation: 'Hello'
        }
    ],
    smart: true
});

You can also use pollerConfig to set smart globally for all pollers.

myModule.config(function(pollerConfig) {
    pollerConfig.smart = true;
});

Always create new poller on calling poller.get

By default poller.get(target, ...) looks for any existing poller by target in poller registry. If found, it overwrites existing poller with new parameters such as action, delay, argumentsArray etc if specified, and then restarts the poller. If not found, it creates and starts a new poller. It means you will never have two pollers running against the same target.

But if you do want to have more than one poller running against the same target, you can force poller to always create new poller on calling poller.get like so:

myModule.config(function(pollerConfig) {
    pollerConfig.neverOverwrite = true;
});

Automatically stop all pollers when navigating between views

In order to automatically stop all pollers when navigating between views with multiple controllers, you can use pollerConfig.

myModule.config(function(pollerConfig) {
    pollerConfig.stopOn = '$stateChangeStart'; // If you use ui-router.
    pollerConfig.stopOn = '$routeChangeStart'; // If you use ngRoute.
});

You also have the option to set pollerConfig.stopOn to $stateChangeSuccess or $routeChangeSuccess.

Automatically reset all pollers when navigating between views

You can also use pollerConfig to automatically reset all pollers when navigating between views with multiple controllers. It empties poller registry in addition to stopping all pollers. It means poller.get will always create a new poller.

myModule.config(function(pollerConfig) {
    pollerConfig.resetOn = '$stateChangeStart'; // If you use ui-router.
    pollerConfig.resetOn = '$routeChangeStart'; // If you use ngRoute.
});

You also have the option to set pollerConfig.resetOn to $stateChangeSuccess or $routeChangeSuccess.

Automatically adjust poller speed on page visibility change

Use the handleVisibilityChange option to automatically slow down poller delay to idleDelay when page is hidden. By default idleDelay is set to 10 seconds.

myModule.config(function(pollerConfig) {
    pollerConfig.handleVisibilityChange = true;
});

myModule.controller('myController', function(poller) {
    poller.get(myTarget, {
        idleDelay: 20000 // Default value is 10000
    });
});

Changelog

https://github.com/emmaguo/angular-poller/releases

Supported Angular versions

Angular Poller supports Angular 1.2.0 - 1.5.x.

License

The MIT License (MIT)

Copyright (c) 2013-2016 Emma Guo

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

angular-poller's People

Contributors

animalupi avatar bdwain avatar emmaguo avatar gugiserman avatar moneytree-doug avatar philjones88 avatar shlomiassaf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular-poller's Issues

Trigger manual poll

Hi,

I have the scenario that we have a set of data refreshing in the background, when a user presses an action button I want to do the action then trigger a manual poll to refresh the data rather than waiting X seconds for the next poll. Is this possible?

Thanks,
Phil

Improvement/Feature Request

This is my use case:
My user requests a file from the backend that needs a few minutes to generate. Here I start the poller, so that the user can continue working and gets notified as soon as the file is ready to download.

I am missing just a single feature in here:
If the user reloads the page the polling is gone (correct me if I am wrong). It would be great if there was an option that remembers the calls in a cookie or in local storage and restarts the polling in case there is a page refresh. So the user gets her files even if she reloads the page.

Thanks for the awesome module!

  • Sven

Poller with resolve and $http

How can I use the poller when I am using a resolve promise to get the data, like this:

  .state('product', {
        url: '/products/{product}/{id}',
        templateUrl: 'products/product-view.html',
        controller: 'ProductViewCtrl',
        resolve: {
          product: ['$stateParams', 'products', function($stateParams, products) {
            return products.get($stateParams.id);
          }]
        }
  });

The products.get function in the factory:

angular.module('bidrp')
.factory('products', [
'$http',

function($http){
  var o = { products: []};

  o.get = function(id) {
    return $http.get('/products/' + id + '.json').then(function(res){
      return res.data;
    });
  };

In the Controller ProductViewCtrl I can do $scope.product = product; to get the data of the resolve.

Can I implement the poller in this case, to sync the product data of the resolve, as soon as a User is within the product-view? How would this be done?

Create NPM package

The module support NPM as is, upload to NPM is needed tough.

Also, look at #53 to be NPM complaint.

Returning the module is optional, and might help NPM users

var poller = require('angular-poller');
// poller === angular.module('emguo.poller');

Poller does not stop on $stateChangeStart

I am using the poller like this in the controller:

var productViewPoller = poller.get('/products/' + $stateParams.id + '.json', { delay: 10000, smart: true, idleDelay: 60000});

productViewPoller.promise.then(null, null, function(resp) {
  $scope.product.bids = angular.copy(resp.data.bids);
  $scope.product.questions = angular.copy(resp.data.questions);
});

// Stop Poller if user changes $state URL
$scope.$on('$stateChangeStart', function (){
  console.log("View closed");
  productViewPoller.stop();
});

I see "View closed" in the console, when I leave / change the $state, but the poller does not stop and keeps running.

New config parameter: maxTries

It would be great to have a maxTries configuration parameter that would stop the poller after that many requests.

If catchError is true, perhaps the notify callback would be called one final time with a special value or throw a special exception which would indicate an interrupt rather than a server error.

deleting a specific poller instance?

Hi,

Have the scenario where I have a "parent" poller running, then when a user clicks an expand link it starts a child poller, inside a controller. When they close the child view, I want it to remove the child poller totally.

Why you ask?
I've had to add "pause" functionality (to stop Chrome issues and save us bandwidth/processing power if people leave the page/tab open by mistake in the background). And I can't use the reset method as it'd clear the parent poller.

I currently use stop() but obviously if they open + close, then tab away (it pauses pollers), then tab back the child poller still exists and starts polling again.

Is it possible to get some kind of "delete" or "delete this instance of a poller" method?

Thanks,

Phil

.startAll() method

Hi, it'll be nice to have a .startAll() or .restartAll() after running .stopAll() to restart the timers on all registered pollers, without having to keep track of each poller / resource object and call .get(myResource);

smart set globally?

Hi,

Just going through and adding smart: true to all our pollers I tried adding it to the pollerConfig as true, that didn't work and checked the source code. Might be helpful to let it be set globally :)

Restangular collection custom method polling issue

Hello. I have made angular-poller work with plain $http string, but when I tried to switch to Restangular, I have encountered an issue. Basically when the app runs, first request is sent successfully, but any request, that should occur after the interval, is not being sent, even though notifyCallback is being triggered with the same, as after the initial request, Restangular object as an argument. I am using a custom Restangular method, so maybe that is the problem? Here's my setup:

// config
RestangularProvider.addElementTransformer('users', true, function (users) {
    users.addRestangularMethod('notifications', 'get', 'notifications');
    return users;
});
// controller
notificationPoller = poller.get(Restangular.all('users'), {
    action: 'notifications',
    delay: 60000,
    smart: true
});
notificationPoller.promise.then(null, null, function (response) {
    // response is a Restangular object with a property notifications which should contain data received from the server
    $rootScope.currentUser.notifications = response.notifications;
});

As I mentioned, when I reload the page, the first request is being sent successfully. After that notifyCallback is triggered without sending a request, so argument(response) passed in is the same. Does angular-poller support custom methods for collections? Any insights would be appreciated.

Init poller withouth start it

Hi, is it possible to initialize a poller withouth starts it?
I need to create a function that start or restart the poller in this way:

    runRanger.start = function(){
        mypoller = poller.get(resource, {
            action: 'jsonp_get',
            delay: config.fastPollingDelay,
            smart: true,
            argumentsArray:[{sysName:indexListService.selected.subSystem,size:1}]
        });       
        mypoller.promise.then(null, null, function(data) {
            console.log(data);
        })
    };

But if i call mypoller.stop() and then runRanger.start(), the promise is triggered twice.

but if i do this way:

        mypoller = poller.get(resource, {
            action: 'jsonp_get',
            delay: config.fastPollingDelay,
            smart: true,
            argumentsArray:[{sysName:indexListService.selected.subSystem,size:1}]
        });       
        mypoller.promise.then(null, null, function(data) {
            console.log(data);
        })

    runRanger.start = function(){
        mypoller = poller.get(resource, {
            argumentsArray:[{sysName:indexListService.selected.subSystem,size:1}]
        });       
    };

it works, but it starts the poller before i call runRanger.start() the first time, i guess the issue is trying to overwrite the promise.
I need to use this function when i change the argumentsArray.
I also tried to add a mypoller.stop() just after the definition but sometimes it starts anyway.

Export the module name

When using angular-poller with CommonJS require statements it's not possible to retrieve the AngularJS module name from the module.

Most AngularJS modules published to npm export the module name string value so they can be used like following example:

angular.module('myApp', [require('angular-resource')]);

Poller breaks on minification

Hello,

when using minification the dependency injection fails.

It could be easily fixed by using the inline annotation, I tried making a pull request (did the fix directly online in github, so hopefully I placed the closing square brakets in the right places :-)

#30

Hope it can be used, ciao!

poller.get doesn't create new pollers for multiple Restangular objects

Hi,

Thanks for this nice library! I think I found an issue with how you're doing the poller lookup (angular.equals). It doesn't seem to work for Restangular objects. Two different objects (different routes) will return true with angular.equals - thus I can't create multiple Restangular pollers. Here is a test case:

    describe('if poller is not registered yet,', function () {

      var r1, r2, r1poller, r2poller;

        beforeEach(function () {

            r1 = Restangular.all('admin');
            r2 = Restangular.all('users');

            r1poller = poller.get(r1, {
              action: 'getList',
              argumentsArray: [],
              delay: 100000
            });


            r2poller = poller.get(r2, {
              action: 'getList',
              argumentsArray: [],
              delay: 100000
            });

        });

        // Passes
        it('should compare properly', function () {
            expect(r1).to.not.equal(r2);
        });

        // Fails
        it('should not be angular.equal', function () {
            expect(angular.equals(r1,r2)).to.equal(false);
        });

        // Fails
        it('should create new poller on invoking get().', function () {
            expect(r1poller).to.not.equal(r2poller);
        });

        // Fails
        it('should increase poller registry size by one.', function () {
            expect(poller.size()).to.equal(2);
        });
    });

Support $interval count param

If I only need to run the poller a single time, right now I have to stop the poller inside the promise. It would be great if we can pass in a param, like count, which could be passed to the underlying $interval the poller code is using telling it to run a number of times.

`target` instead of `self`

target[action].apply(self, argumentsArray);

current =
                                target[action].apply(self, argumentsArray);

If you are running apply here then it makes sense to always use the target for context to run with itself, so then the this context doesn't change. In my case, I have helpers wrapped around my $http and $resource , and it's trying to access this which is the poller object.

Proposed change:

current =
                                target[action].apply(target, argumentsArray);

Thoughts before I make a PR?

Provide feedback of server timeout/error

I'd love to see this thing expanded just enough so that the promise returned errors when the server responded with 502, or timed out.

This way one could catch that and do something with it. My use case is I want to give a visual indicator in the UI.

I have a workaround for not having this, but it sure would be nice. Thanks!

promise that is resolved on each call to backend

I am trying to figure out how to get the promise that is resolved each time the poller ticks. I want to show a quick busy indicator starting when the poller goes to the backend and ending when the callback is complete. Is this possible without changing the poller?

Getting a poller for an existing resource results in duplicate intervals.

Hi Emma, Thank you for this wonderful work!

I found that if I call poller.get with an existing resource, even though the same entry from the factory pollers array is used, a new $interval delay is added in the start method because current is null. The result is that calling get does not work just to change the options on a poller for an existing service as is implied by the else { poller.set(options); poller.restart(); } in the get method. If you call it this way you will get an exponentially increasing number of $intervals set and your notify method will start getting called an exponentially increasing number of times.

Perhaps something more is needed for cleanup here?

Best regards =)

ui-router resolve?

Is there support for ui-router's resolve? Something where we could $watch the promise and update using normal angular methods?

Example for usage with http on the server side

Could anybody provide an example / boilerplate for usage of this with the appropiate server side code? I looked into the test specs, but I dont exactly know how to code the server side, e.g. node.js.

Replacing Resource with angular-poller

Previously I had:

$scope.person = Person.get(resourceParams);

which I changed to:

var pollerQuery = poller.get(Person, {action: 'get', smart: true, argumentsArray:[resourceParams]});
pollerQuery.promise.then(null, null, function (data) {
    $scope.person = data;
});

but now I get the following error:

Error: [$interpolate:interr] Can't interpolate: {{ person | personLink }}
TypeError: Cannot read property 'first_name' of undefined

I assume this is because I had previously been assigning $scope.person but it is now left undefined until the first request completes.

What is the correct solution here?

Keep existing myPoller.promise updated after calling .restart()

myPoller.promise does not get notified correctly in the following case:

var myPoller = poller.get(myResource);
myPoller.promise.then(...); //It doesn't get notified anymore after calling .restart()

myPoller.restart();
myPoller.promise.then(...); //This one works fine.

How to pass an argument into the factory to construct a dynamic url

I need to be able to pass an argument into the factory to construct a dynamic url so that 'greet' is called with a newTime arg.
How can I modify poller.get() to pass in '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' }
    });
})

Stopping poller on error

Hi,

I am relatively new to AngualrJS and I have been trying to integrate your poller. My question is how could I make it so that the poller stops on error (e.g. 404 or 503)?

I am following the code from your examples, my code (bit trimmed) looks like this:

somePoller = poller.get(res.task, {
    action: 'get',
    delay: 1000,
    params: {
        id: 111
    }
});
somePoller.promise.catch(function(e) {
    console.log('error', e);
});
somePoller.promise.then(function(e) {
    console.log('success', e);
}, function(e) {
    console.log('fail', e);
}, function(data) {
    console.log('data', data);
});

When there's an error, neither the catch nor the then part seem to be triggered. I am assuming I am doing some rookie mistake here but I would really appreciate it if you could help me pinpoint it.

Thanks in advance!

Should poller.get really start a poller by default?

I've recently been experimenting with this module, and needed to add some error handling.

However, I was getting some unexpected requests happening. The aim was to back off the poller on error. So I was using poller.get(target,{delay: newInterval}); to set the interval. However when I looked at the get code here, I see it always starts the poller, causing another immediate request.

get: function (target, options) {

                    var poller = findPoller(target);

                    if (!poller) {

                        poller = new Poller(target, options);
                        pollers.push(poller);
                        poller.start();

                    } else {

                        poller.set(options);
                        poller.restart();
                    }

                    return poller;
                },

I can see that this is a nice simple way to get the poller running, especially a restart with new values, but it doesn't fit with the semantics of the the method name. It isn't mentioned in the doc string either. The get method is for getting a poller instance. You have a good api for giving the developer control of the api, why not let them control the poller instance?

Perhaps adding an autostart option to the poller which is false by default could be an option. That way if the developer wants it to start up on get, then they can do so.

The problem was, the immediate request on the get, caused the error handling to be fired again by the get method in the errorHandling, (I was simulating a server error). This meant things got pretty out of hand on the request front very quickly. I've handled it now, but it feels a bit hacky.

Incidentally, the error handling I wanted to add was incremental back off on error, and interval jitter. I think these 2 things could be offered as core, and are good practice if you are polling at scale.

The back off means the qps on server should reduce should something unexpected happen and the jitter avoids metronomic requests, which also at scale can cause problems.

I have forked, and may well add these in and would be happy to do a PR if you were interested in these features.

Problem Reusing Resource with get and query

I am using the same resource twice in two difference routes.

var pollerQuery = poller.get(Info, {action: 'query', smart: true});
var pollerQuery = poller.get(Info, {action: 'get', smart: true, 
   argumentsArray:[{infoId: $routeParams.infoId}]});

Between routes, I should be calling stop:

routed.config(function (pollerConfig) {
    pollerConfig.stopOnStateChange = true; // If you use $stateProvider from ui-router.
    pollerConfig.stopOnRouteChange = true; // If you use $routeProvider from ngRoute.
});

This leads to:

Error: [$resource:badcfg] Error in resource configuration for action `query`. Expected response to contain an array but got an object

I think there is some issue with the equality of Pollers / getmethod and reusing the Poller.

Multi pollers, stop specific one when state changed, not "stopAll"

Hi Emma,

First of all, thanks for this great module, nice job!

Here is the situation, I have two pollers: poller-A for all pages and poller-B for only one page. I just want poller-B only work in the specific page, so I use "pollerConfig.stopOnStateChange = true" to stop it when state changed, but this will stop all pollers while I want to keep poller-A still working.

Is there anything I can do to implement this? Coule you please help?

Thanks again,
Lee

Access Response Header on Success

Is there any way to access the response headers (on success)?

The docs have this comment:

// Error handler: (data, status, headers, config)

Consecutive requests not working with $http configuration

After updating from 0.4.2 to 0.4.3 I'm having some issues with consecutive requests (the first request is still sent) when using a $http configured poller (I have not tried $resource or Restangular). Each consecutive request yields the following error:

angular.js:12783 Error: [$http:badreq] Http request configuration url must be a string.  Received: undefined
http://errors.angularjs.org/1.4.10/$http/badreq?p0=undefined
    at http://localhost:3000/bower_components/angular/angular.js:68:12
    at $http (http://localhost:3000/bower_components/angular/angular.js:10498:30)
    at Function.$http.(anonymous function) [as get] (http://localhost:3000/bower_components/angular/angular.js:10743:18)
    at b (http://localhost:3000/bower_components/angular-poller/angular-poller.min.js:2:1334)
    at http://localhost:3000/bower_components/angular/angular.js:15179:52
    at Scope.$eval (http://localhost:3000/bower_components/angular/angular.js:16359:28)
    at Scope.$digest (http://localhost:3000/bower_components/angular/angular.js:16175:31)
    at Scope.$apply (http://localhost:3000/bower_components/angular/angular.js:16467:24)
    at tick (http://localhost:3000/bower_components/angular/angular.js:11598:36)

My code:

poller.get('api/ladder', {
    delay: 5000
});

Multiple Pollers Cause Blocking

I'm running into an issue that when I have two pollers, I am noticed blocking that increases over time when trying to execute other code such as unrelated $http calls.

I haven't had time to create a fiddle yet as my use case is a little complex, however, I've already made the fix to the angular-poller library locally that alleviates. I've forked the repo and will initiate a pull request once checked in.

Using a service that returns $http?

Hi,

Is it possible to do the following:

Have a service:

app.service('fooService', function($http) {
  this.list = function () {
    return $http.get('/api/foos');
  };
});

Which should be used for the resolve and the polling.

app.config(function ($stateProvider) {
  $stateProvider.state('foos', {
    url: '/foos',
      resolve: {
        foos: function (fooService) {
          return fooService.list();
        }
      },
      views: {
        'content@': {
          templateUrl: 'foos.html',
          controller: 'FooCtrl'
        }
      }
    });
});

With this controller:

app.controller('FooCtrl', function($scope, $log, poller, fooService, foos){
  $scope.foos = foos.data;

  var fooPoller = poller.get(fooService.list(), { delay: 5000 });

  fooPoller.promise.then(null, null, function (results) {
    $log.debug('Poller');
    $scope.foos = results.data;
  });
});

As I just end up with a JS console error of:

TypeError: Cannot read property 'apply' of undefined

Thanks,

Phil

Multiple request at same time and smart config it's true

I had smart with true value in poller config and sometimes i see in browser request, 2 or 3 pending requests at the same time. When requests gives timeout , are again started.This should not be avoided with the option smart : true?

I need to change something to only send new request if the previous one is resolved?

Restangular.all doesn't return a restangular collection

So I've been struggling to get angular-poller to do some polling for a series of restangular objects in the app I'm building. I figured it would be relatively easy to do.. plug in the promise in my directive that is in the restores, then account for it in my controller instead of the actual data using the .promise.then pattern.

However, it appears that angular-poller handles collections correctly. Instead of handing me a collection, I keep getting an array with individual restangular objects. This is a problem.

TypeError: Cannot read property 'toString' of undefined

I can get .one to work, but .all fails. The second segment of code works fine, and updates $scope with values perfectly! The imgur shows the error and output. Any help would be appreciated!

http://imgur.com/BSx3CdY

    var one = Restangular.one('keyword', 51);
    var two = Restangular.all('keyword');
    console.log(two);
    console.log(two.getList());

    var myPoller = poller.get(two , {
        action: 'get',
        delay: 5000,
        smart: true,
        argumentsArray: []

    });
    myPoller.promise.then(null, null, callback);

   //Works fine
      Restangular.all('keyword').getList() 
        .then(function (users) {
            $scope.user = users[0];
            console.log(users[0].user);
            console.log(users[0]);
            username = users[0].user;

        })

{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 2}, "objects": [{"created": "2015-11-20T02:02:20", "id": 69, "is_active": true, "keyword": "Hello", "resource_uri": "/api/v1/keyword/69/", "slug": "Hello", "updated": "2015-11-20T02:02:28.973600", "user": "/api/v1/users/1/"}, {"created": "2015-11-20T02:02:39.508467", "id": 70, "is_active": true, "keyword": "Hi", "resource_uri": "/api/v1/keyword/70/", "slug": "Hi", "updated": "2015-11-20T02:02:39.513537", "user": "/api/v1/users/1/"}]}

angular 1.4 support

it seems like the current state of this project would work in angular 1.4. Would it be possible to update the bower dependency to allow angular 1.4?

Thanks

Document creating multiple pollers in single injection

Hi, thanks for the module, it's very well done and full-featured. May I recommend documenting how to create multiple instances for multiple resources within a single injection? E.g.:

var myPoller1 = new poller.get(myResource1);
var myPoller2 = new poller.get(myResource2);

Then poller.stopAll() would make more sense and one can use $q.all() and map the responses.

$resource params

Hello,

Could you help me with doubt?

I have one resource:

function Notification ($resource) {
    return $resource('/api/notifications/:type/:notificationId/:action',
              {type: '@type', notificationId: '@notificationId', action: '@action'},
              {
                update: {method:'PUT'},
                poller: {method: 'GET', ignoreLoadingBar: true}
              });
  }

As I would call the poller and send the params
{type: '@type', notificationId: '@notificationId', action: '@action'}

var = myPoller poller.get (Notification, {action: 'poller', delay: 6000});

Tks

JWT and Restangular instance

Hi,

I'm having some trouble using poller with Restangular instance and JWT authentication.
Once user has logged in, Restangular is configured to send Authorization header with a JWT. When the token has expired and user log in once again, default headers sent by restangular are updated. Every api calls i made this way are working fine, but poller instances are still using the same restangular instance with the previous token, even by doing a poller.reset(); after token expiration.

Here is the way i'm providing the promise :
poller.get(chatService.getNewMessages(), {
action: 'getList',
catchError: true,
delay: 2000
}
);

chatService is my restangular service, and as every services are singletons, I really have no idea why and where an old instance is persisted. Any Idea ?

Poller throwing Error: [$resource:badcfg] array

Somehow when $resource is used in the poller, it's expecting an array, in spite of the object I'm giving it. I'm calling it like this:

      var myResource = $resource("/user/current")
      var myPoller = poller.get(myResource)
      var callback = function(resp){
        console.log("data!", data)
      }
      myPoller.promise.then(null, null, callback)

In response it throws an error complaining that Response does not match configured parameter

And I'm definitely sending an object back from the server, not an array, which I can verify by checking the network tab:

{
    "user": {
        "created": "2013-10-31T21:11:28.010854", 
        "email": "[email protected]", 
        "email_hash": "6ac7fd173d257d9913b2a7aa8d079021",
        ...
}

Interestingly, when I send wrap the above in an array (like [ {"user": {...} } ] it works, sorta...the callback gets an array, the first item of which is the actual response item. Unfortunately that's not a viable fix since other client code relies on these endpoints returning objects.

I'm using ng-resource 1.2.16, same as the example. Would love to figure out how to make this work, it's a great little service I'd love to use all over our app. Thanks for the help!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.