Home > Net >  Function running unnecessarily
Function running unnecessarily

Time:11-10

I have code like this

this.service.function().subscribe(data :any) => {
   this.array = data
   this.flat(this.array)
});

My problem is the flat function is running unnecessarily several times. I only want to this to run when this.array got some values.

How do I deal with this? Thanks

CodePudding user response:

You can use a filter operator to check whether data has values or not (data.length check). It will take of only run the subscription if array contains values.

import { filter } from 'rxjs/operators'

this.service.function().pipe(
   filter(d => d.length)
).subscribe(data => {
   this.array = data
   this.flat(this.array)
});

CodePudding user response:

Try this:

this.service.function().subscribe(data => {
this.array = data
if (data.length > 0) {
  this.flat(this.array)
}
}
);
  • Related