Home > Software design >  ERROR RangeError: Invalid array length in angular
ERROR RangeError: Invalid array length in angular

Time:09-23

I have angular version 14. I am having this error. When i click Review button, this error is coming and Reviews aren't showing

ERROR RangeError: Invalid array length

Error Screenshot

My Code

<div  *ngIf="rating && total_rating">
   <div >
      <svg width="16" height="16"  viewBox="0 0 24 24"  *ngFor='let in of counter(rating) ;let i = index'>
<path
d="M16.2 8.16l4.74.73a1.23 1.23 0 01.67 2.11l-3.46 3.28a1.23 1.23 0 00-.37 1.1l.77 4.68a1.24 1.24 0 01-1.82 1.29L12.5 19.1a1.28 1.28 0 00-1.16 0l-4.27 2.17A1.25 1.25 0 015.27 20l.85-4.68a1.19 1.19 0 00-.34-1.09l-3.41-3.4a1.23 1.23 0 01.71-2.1l4.75-.64a1.26 1.26 0 00.95-.67l2.16-4.24a1.25 1.25 0 012.24 0l2.09 4.28a1.22 1.22 0 00.93.7z">
</path>
</svg><span >({{rating}})</span><span >({{total_rating}})</span>
   </div>
</div>

And

  counter(i: number) {
    return new Array(i);
}

Review Button

<div   (click)="getReviews(item.offer_by.id)">   
   <button type="button"  >Reviews</button>
</div>

on these two console is pointing error.

CodePudding user response:

This exception is because the id passed by the counter to Array(i) is less than 0 or greater than (2^32) -1 ie 4294967295. See exception

You can put a limit using Math.max and Math.min like this

counter(i: number) {
    if (i === NaN) return Array(0);
    return new Array(Math.max(0, Math.min(4294967295, i)); // limit b/w 0 and 4294967295
}

Alternatively

counter(i: number) {
   if ( i < 0 || i === NaN ) return Array(0);
   else if ( i > 4294967295) return Array(4294967295);

   return Array(i);
}
  • Related