1

I'm triggering a function on setInterval() to basically do an HTTP GET calls every 30s however every time it triggers it duplicates the data as they're being pushed in an array.

The idea of the for() is to find every objects with status of AwaitingPicking and AwaitingCollection then push them to their respective array.

private awaitingPicking: any = [];
private awaitingCollection: any = [];

constructor(private sharedService: SharedService, private http: Http) {
    setInterval(() => {
      this.getOrdersFromOrigin();
    }, 10000);
  }

getOrdersFromOrigin() {
    this.isLoading = true;
    this.sharedService.getOriginSite()
      .subscribe(data => {
        this.isLoading = false;

        for (var i = 0; i < data.Results.length; i++) {
          var element = data.Results[i];
          if (element.OrderLineGroups[0] && element.OrderLineGroups[0].Status == 'AwaitingPicking') {
              this.awaitingPicking.push(element);
          } else if (element.OrderLineGroups[0] && element.OrderLineGroups[0].Status == "AwaitingCollection") {
            this.awaitingCollection.push(element);
          }
        }

      },
      err => {
        this.isLoading = false;
      });
  }

Is there a way to prevent the data from duplicating every time the setInterval() triggers?

I tried something like the code below but it still duplicating the element.

if(this.awaitingPicking.indexOf(element) === -1){
  this.awaitingPicking.push(element);
}
MrNew
  • 1,384
  • 4
  • 21
  • 43
  • Does you response items have any unique id? If yes then you can use it to filter out duplicate item before pushing to array – Anupam Nov 29 '16 at 11:20
  • Yeah, can show an example how to filter it correctly? (element) is a whole object so each objs have unique id. – MrNew Nov 29 '16 at 11:27
  • Follow [this post](http://stackoverflow.com/questions/30735465/how-can-i-check-if-the-array-of-objects-have-duplicate-property-values) to see how to eliminate duplicate objects from an array. You need to use some unique field from your object though – Anupam Nov 29 '16 at 11:29

1 Answers1

1

Only push to the "awaitingPicking" and "awaitingCollection" array if the element does not exist. See e.g. the answer to this question for a way to do this (you need to refactor to typescript off course).

You could for example add something like the following to your class (you also need to implement this for awaitingCollection):

private pushAwaitingPickingIfNew(element: any): void {
    if(!this.awaitingPicking.some(a => a == element)) {
        this.awaitingPicking.push(element);
    }
}

and then replace

this.awaitingPicking.push(element)

with

this.pushAwaitingPickingIfNew(element);
Community
  • 1
  • 1
Sandhje Bouw
  • 172
  • 1
  • 6