angular - 通过 filter 方法给出的对象(对于 material.angular.io 自动完成字段)变得未定义
问题描述
我试图实现angular.material.io的自动完成功能。但是,在尝试在我的代码中对其进行编码时,我遇到了未定义参数的错误。我不知道为什么会这样。
这是我实现的打字稿代码。
export class BooksComponent implements OnInit {
private books: Array<Book> = [];
//Autofillers & form controllers
private bookCtrl = new FormControl();
private filteredBooks: Observable<Book[]>;
constructor() {
//Replace this in the future with data passed from the API
JSONBooks.forEach(book =>
this.books.push(new Audiobook(book.title, book.description, book.ISBN, book.image, book.price, book.amazonLink,
book.publisher, book.amountOfChapters, book.soldCopies, book.adaptedForScreens, book.dateAdded, book.rating, book.amountOfHours))
);
//Formcontrol and autofills
if (this.books) {
this.filteredBooks = this.bookCtrl.valueChanges
.pipe(
startWith(''),
map(book => book ? this.filterBooks(book) : this.books.slice())
);
}
}
ngOnInit() {}
private filterBooks(value: Book): Book[] {
return this.books.filter(
//Matches book title
book => book.getTitle.toLowerCase().indexOf(value.getTitle.toLowerCase()) === 0
);
}
}
这是我实现的 HTML 代码。
我想找一本同名的书
</p>
<form>
<mat-form-field>
<input matInput placeholder="Title" aria-label="Title" [matAutocomplete]="auto" [formControl]="bookCtrl">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let book of filteredBooks | async" [value]="book.getTitle">
<span>{{book.getTitle}}</span>
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
<p>
控制台输出,第 118 行是指我的打字稿代码,本节:.indexOf(value.getTitle.toLowerCase())
core.js:15723 ERROR TypeError: Cannot read property 'toLowerCase' of undefined
at books.component.ts:118
at Array.filter (<anonymous>)
at BooksComponent.push../src/app/books/books.component.ts.BooksComponent.filterBooks (books.component.ts:116)
at MapSubscriber.project (books.component.ts:62)
at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:35)
at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber.notifyNext (mergeMap.js:84)
at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/InnerSubscriber.js.InnerSubscriber._next (InnerSubscriber.js:15)
at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
at SafeSubscriber.schedulerFn [as _next] (core.js:13514)
我检查了多次,但似乎无法在我的代码中找到问题。
注意:this.books
确实被填充并且可以读取属性。诸如此类的方法book.getTitle
也有效。不知何故,该对象没有传递给 filterBooks 方法。
解决方案
添加一个简单的 if 条件来检查value
is not null
this.books.filter(
//Matches book title
book => {
if(!value.getTitle) return false
return book.getTitle.toLowerCase().indexOf(value.getTitle.toLowerCase()) === 0
} );