javascript - Angular 6:錯誤 TypeError:el.toLowerCase 不是一個函數
我正在我的應用程式中創建一個簡單的過濾管道,這是我所擁有的。
過濾元件:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'dataFilter'
})
export class DataFilterPipe implements PipeTransform {
transform(value: any[], input: string) {
if (input) {
input = input.toLowerCase();
return value.filter(function (el: any[]) {
return el.toLowerCase().indexOf(input) > -1;
});
}
return value;
}
}
這裡是 componet.html
<div class="card movies-list" id="movies-list">
<div class="card-header movies-list_header">
<h1>Content: <small>Best movies of 2010's</h1>
</div>
<div class="card-body">
<div class="row movies-list_filter">
<div class="col-md-2">Filter By</div>
<div class="col-md-4">
<input type='text' [(ngModel)]="listFilter">
</div>
</div>
<div class="row">
<div class="col-md-6">
<h1>filterdbY: {{listFilter}}</h1>
</div>
</div>
<table class="table table-striped table-responsive">
<thead>
<tr class="movies-list_tbheader">
<td></td>
<th>Title</th>
<th>Realease</th>
<th>Rating</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr class="movies-list_data" *ngFor="let movie of movies | dataFilter:listFilter">
<td>
<img *ngIf="movie.poster_path" class="thumbnail" src="http://image.tmdb.org/t/p/w500/{{movie.poster_path}}">
</td>
<td>{{ movie.title }}</td>
<td>{{ movie.release_date }}</td>
<td>{{movie.vote_average}}</td>
<td>{{movie.overview}}</td>
</tr>
</tbody>
</table>
</div>
</div>
在 component.ts 中,我這樣宣告了變數 listFilter:
export class MoviesComponent implements OnInit {
listFilter = '';
-----------
}
當我運行我的應用程式並嘗試搜尋一些文字時,我收到以下錯誤
錯誤 TypeError:el.toLowerCase 不是一個函數
我的程式碼有什麼問題?任何幫助都會感激
答案#1
使用管道來過濾數據並不被認為是「最佳實踐」。相反,應該在你的組件中進行。例如:
// Local filter
performFilter(filterBy: string): IMovie[] {
if (filterBy) {
filterBy = filterBy.toLocaleLowerCase();
return this.movies.filter((movie: IMovie) =>
movie.title.toLocaleLowerCase().indexOf(filterBy) !== -1);
} else {
return this.movies;
}
}
我在這裡有一篇關於這個的詳細部落格文章:https://blogs.msmvps.com/deborahk/filtering-in-angular/
它詳細說明了為什麼不應該使用管子進行過濾,以及執行上述過濾操作的幾種不同技術。
順便說一下……這段代碼看起來真的很熟悉。:-) 這是我以前的一場 Angular v2 講座中的代碼……在我們被團隊通知說不建議這樣使用管道之前。
哦……我還看了你在另一個答案中作為評論提供的鏈接(該答案後來已被刪除),代碼與你上面發布的並不相同。這是你鏈接中的“可用”代碼:
transform(value: IProduct[], filterBy: string): IProduct[] {
filterBy = filterBy ? filterBy.toLocaleLowerCase() : null;
return filterBy ? value.filter((product: IProduct) =>
product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1) : value;
}
這裡是上方的程式碼:
transform(value: any[], input: string) {
if (input) {
input = input.toLowerCase();
return value.filter(function (el: any[]) { // <---- data type!
return el.toLowerCase().indexOf(input) > -1;
});
}
return value;
}
注意傳遞給過濾函數的資料類型是 any[]。它應該只是 any。
