【问题标题】:ERROR TypeError: Cannot read property 'filter' of undefined typescript错误类型错误:无法读取未定义打字稿的属性“过滤器”
【发布时间】:2019-03-13 03:42:10
【问题描述】:

我想根据左侧点击的作者过滤书籍列表。作者和书籍在不同的数组中,所以当我点击 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);
    });
  }
}

【问题讨论】:

    标签: angular typescript filter


    【解决方案1】:

    当传入数据为'null'并且过滤器方法期望数据时会导致此错误,因此,这会导致错误。

    1) 尝试检查数据是否存在
    或
    2)您最初可以提供一个空数组。不确定这是否有效

    books: Book[] = [];
    

    你能看看这是否有效吗?

    【讨论】:

    • 你是对的,但我做了 if 条件,所以它现在可以工作了,谢谢。
    • @AhmedShaarawy 很高兴你修复了它!
    【解决方案2】:

    使用 subscribe 作为返回书籍的方法:

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

    【讨论】:

    • 它可以在点击时工作但不能点击,意味着当更改作者不更改书籍时
    • 你在 this.route.params.subscribe() 中使用过 this.booksService.getBooks().subscribe() 吗?
    【解决方案3】:

    您需要过滤 this.books 而不是 this.booksService.books

     this.filteredBooks = this.books.filter(item => item.author === this.id);
    

    【讨论】:

    • 它仍然给我 ERROR TypeError: Cannot read property 'filter' of undefined
    • @AhmedShaarawy,像这样设置变量books: Book[] = []; 而不是books: Book[]; this..
    猜你喜欢
    • 2021-12-31
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    • 2018-04-29
    相关资源
    最近更新 更多