错误TypeError:无法读取未定义打字稿的属性'filter'

时间:2018-10-08 12:51:44

标签: angular typescript filter

我想根据左侧单击的作者过滤书籍列表。作者和书籍位于不同的数组中,因此在使用route.params单击并尝试根据该ID来过滤书籍时,我得到了作者ID。

如何与点击的作者一起过滤右边的书?

    import { Component, OnInit } from '@angular/core';
import { BooksService } from '../shared/books.service';
import { ActivatedRoute, Params } from '@angular/router';
import { Book } from './book.model';

@Component({
  selector: 'app-books',
  templateUrl: './books.component.html',
  styleUrls: ['./books.component.scss']
})
export class BooksComponent implements OnInit {
  books: Book[];
  filteredBooks: Book[];
  id: string;

  constructor(
    private booksService: BooksService,
    private route: ActivatedRoute
  ) {}



  ngOnInit() {
    this.booksService.booksChanged
    .subscribe(
      (books: Book[]) => {
        this.books = books;
      }
    );
    this.books = this.booksService.getBooks();

    this.route.params.subscribe((params: Params) => {
      this.id = params['id'];
      this.filteredBooks = this.booksService.books.filter(item => item.author === this.id);
      console.log(this.filteredBooks);
    });
  }
}

enter image description here

3 个答案:

答案 0 :(得分:1)

使用订阅作为返回图书的方法:

this.booksService.getBooks().subscribe(books => {
  this.filteredBooks = books.filter(item => item.author === this.id);
});

答案 1 :(得分:0)

您需要从 this.books 中进行过滤,而不是从 this.booksService.books

中进行过滤
 this.filteredBooks = this.books.filter(item => item.author === this.id);

答案 2 :(得分:0)

此错误是由于传入数据为“ null”而导致的,并且过滤器方法正在获取数据,因此,导致了该错误。

1)尝试检查数据是否存在

2)您最初可以提供一个空数组。不确定是否可以

books: Book[] = [];

您能看到这行吗?