问题
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),
);
}
回答1:
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>
回答2:
The safe navigation operator ( ?. ) and null property paths
The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths. Here it is, protecting against a view render failure if the currentHero is null.
So in your example you can also use The safe navigation operator ( ?. ):
<div class="suggestion" *ngIf="results?.length > 0">
<div *ngFor="let result of results ">
<a href="" target="_blank">
{{ result.name }}
</a>
</div>
</div>
回答3:
Initializing the variable to empty solved my issue.
DoctorList: any[] = [];
回答4:
you can just initialise your array in declaration :
result: Array<any>;
if the probleme style persiste you should check of null in your method lik this :
onSearch(name) {
this.search
.searchEmployee(name)
.subscribe(
name =>
if(name!=null){
this.results =
name,//alert(searchName),this.route.navigate(['/information/employees/']),
}
error => alert(error),
);
}
来源:https://stackoverflow.com/questions/44689474/error-typeerror-cannot-read-property-length-of-undefined