错误TypeError:无法读取未定义的属性'length' [英] ERROR TypeError: Cannot read property 'length' of undefined

查看:245
本文介绍了错误TypeError:无法读取未定义的属性'length'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码的这一部分有错误

There is an error in this part of my code

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

但是当我检查资产文件夹时,gms-logo.png仍然存在,而在angular-cli.json中,资产也存在.路径也是正确的.

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?

下面是我用于搜索的html及其建议段的显示

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>

下面是我的组件

results: Object;



 onSearch(name) {
            this.search
            .searchEmployee(name)
            .subscribe(
                name => this.results = name,//alert(searchName),this.route.navigate(['/information/employees/']),
                error => alert(error),
                );
}

推荐答案

您需要将results变量初始化为数组.

You need to initialize your results variable as an array.

在您的组件中,添加:

results = [];

另一种选择是更改建议div的*ngIf语句,以检查是否定义了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>

这篇关于错误TypeError:无法读取未定义的属性'length'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆