Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ERROR TypeError: Cannot read property 'length' of undefined

There is an error in this part of my code

<img src="../../../assets/gms-logo.png" alt="logo" routerLink="/overview" alt="website icon">

But when I checked the assets folder, gms-logo.png is still there and in angular-cli.json, assets is also there. The path is also correct.

Recently though, I've been working on Search function. So my hypothesis is,

Has the program started searching even if the user is still not focused on the input type? How do I fix this?

Below is my html for Search and the showing of its suggestion segment

<input type="text" placeholder="Search" (keyup)="onSearch($event.target.value)">        
<div class="suggestion"  *ngIf="results.length > 0">
     <div *ngFor="let result of results ">
          <a href="" target="_blank">
                {{ result.name }}
          </a>
     </div>
</div>

Below is my component

results: Object;



 onSearch(name) {
            this.search
            .searchEmployee(name)
            .subscribe(
                name => this.results = name,//alert(searchName),this.route.navigate(['/information/employees/']),
                error => alert(error),
                );
}
like image 463
Char Avatar asked Jun 22 '17 03:06

Char


People also ask

How do you solve TypeError Cannot read property length of undefined?

The "Cannot read property 'length' of undefined" error occurs when accessing the length property on an undefined value. To solve the error, make sure to only access the length property on data types that support it - arrays or strings.

What does Cannot read property length of undefined mean?

TypeError: Cannot read property 'length' of undefined. TypeError is a subset of JavaScript Error that is thrown when code attempts to do something that does not exist on the target object. This message indicates that our code expects to have an object with a length property, but that object was not present.

What does Cannot read property toString of undefined mean?

The "Cannot read property 'toString' of undefined" error occurs when the toString() method is called on an undefined value. To solve the error, make sure to only call the toString method on data types that support it.


1 Answers

You need to initialize your results variable as an array.

In your component, add:

results = [];

Another option is to change your suggestion div's *ngIf statement to check if results is defined:

<div class="suggestion"  *ngIf="results">
   <div *ngFor="let result of results ">
          <a href="" target="_blank">
                {{ result.name }}
       </a>
   </div>
</div>
like image 117
Levi Fuller Avatar answered Oct 06 '22 09:10

Levi Fuller