【问题标题】:Angular Observable filtering doesn't workingAngular Observable 过滤不起作用
【发布时间】:2021-07-23 05:17:46
【问题描述】:

我有一个 Observable 数组,我想通过一些属性对其进行过滤。但是,过滤不起作用。 我尝试调试代码,但它好像没有进入pipe(map(... 部分。

ngOnInit() {
    this.bookService.getBooks().subscribe(res => {
      this.store.dispatch(listBooks({ books: res }));
    });

    this.filterForm = this.formBuilder.group({
      name: [""],
      author: [""],
      release_year: [""]
    });

    this.filterForm.valueChanges.subscribe(val => {
      this.books$.pipe(map(books => 
        books.filter(b => {
          return b.name.startsWith(val.name) &&
          b.author.startsWith(val.author) &&
          b.release_year.startsWith(val.release_year)
        })
      ))
    })

【问题讨论】:

    标签: angular typescript rxjs observable


    【解决方案1】:

    这行代码永远不会执行 这本书$.pipe( 因为你没有订阅它。任何 observable 都需要订阅才能执行。

    最好改成下面的代码:

      this.filterForm.valueChanges
      .pipe(
       withLatestFrom(this.books$),
       map(([val,books])>
          books.filter(b => {
            return b.name.startsWith(val.name) &&
            b.author.startsWith(val.author) &&
            b.release_year.startsWith(val.release_year)
          })
       ))
       .subscribe(books => {
        this.books=books;        
       ))  
    

    【讨论】:

      【解决方案2】:

      这看起来不像是一个完整的例子——例如this.book$ 是什么?

      此外,您的 pipe() 似乎并没有以 subscribe() 结尾 - 所以永远不会做任何事情

      【讨论】:

      • 谢谢,subscribe() 解决了我的问题。
      • 很高兴为您提供帮助。请接受这个作为答案 - 谢谢。
      猜你喜欢
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-15
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      • 2017-03-02
      相关资源
      最近更新 更多