admin管理员组

文章数量:1356847

I'm trying to push an item to an array every 5 seconds in an AngularJS service, but I keep getting 'items is not defined' after 1 item is added dynamically...

I've been playing with this simple code for over an hour now, I'm sure it's something silly but I can't figure it out. :/

app.service('ItemService', function() {

  var items = [9000];

  this.addItem = function () {
    items.push(Math.random());
  }

  setInterval(this.addItem(), 5000);

  return {
    get: function() {
      return items;
    }
  }
});

Plnkr:

I'm trying to push an item to an array every 5 seconds in an AngularJS service, but I keep getting 'items is not defined' after 1 item is added dynamically...

I've been playing with this simple code for over an hour now, I'm sure it's something silly but I can't figure it out. :/

app.service('ItemService', function() {

  var items = [9000];

  this.addItem = function () {
    items.push(Math.random());
  }

  setInterval(this.addItem(), 5000);

  return {
    get: function() {
      return items;
    }
  }
});

Plnkr: http://plnkr.co/edit/EVFUww7dfUAJzQqth7mx

Share Improve this question asked Feb 17, 2015 at 8:50 user1960364user1960364 2,0096 gold badges29 silver badges48 bronze badges 3
  • try this.items.push()... – Rakesh_Kumar Commented Feb 17, 2015 at 8:52
  • 1 @SearchAndResQ why is that wrong? its a new array with 9000 in it? – Chris Charles Commented Feb 17, 2015 at 8:54
  • @SearchAndResQ - It isn't wrong - It creates an array with one item at index:0 with value 9000. – techfoobar Commented Feb 17, 2015 at 8:54
Add a ment  | 

4 Answers 4

Reset to default 4

You're using angular, so you shouldn't be doing setInterval, but rather use the $interval service provided by Angular.

That, coupled with the correct observation of @techfoobar, would result in the correct behavior you are looking for:

app.service('ItemService', ['$interval', function($interval) {

  var items = [9000];

  this.addItem = function () {
    items.push(Math.random());
  }

  $interval(this.addItem, 5000); 

  return {
    get: function() {
      return items;
    }
  }
}]);

Working Plunker.

You are calling addItem() and passing its return value to setInterval() - instead of the function itself.

It should be:

setInterval(this.addItem, 5000); // no () after addItem

try using $interval() service instead of setInterval

$interval($scope.item, "time_interval"); 

Timing function like window.setInterval, in angularjs are wrapped in $interval (https://docs.angularjs/api/ng/service/$interval). Angular manages interval function like a promise to ensure more control over timer.

本文标签: javascriptUncaught ReferenceError items is not definedStack Overflow