【问题标题】:Not able to use filter in observable list of objects using typescript无法使用打字稿在可观察的对象列表中使用过滤器
【发布时间】:2020-12-26 17:45:02
【问题描述】:

试图过滤 Observable List 中的对象列表。

型号:

export class Month {
  id: string;
  description: string;
}

价值观:

描述:“一月” 编号:“01”

描述:“二月” 编号:“02”

描述:“三月” 编号:“03”

在我的服务中,我尝试返回带有所选值的列表,在这种情况下只有一个,但将来可能会更多。

  selectedMonth: string = "02";
    public getMonths(): Observable<Month[]> {
        return of(this.MONTHS).pipe(
          map(months => {
            months.filter(month => {
              month.id === this.selectedMonth;
            });
            return months;
          })
        );
      }

但似乎过滤器根本不起作用,我总是得到整个列表(12 个元素,而不是一个元素)

ngOnInit(): void {
    this.monthservice.getMonths().subscribe(months => (this.months = months));

    console.log(this.months);
  }

此链接有代码:

https://stackblitz.com/edit/angular-myfilter?file=src/app/services.ts/month.service.ts

有什么帮助吗?

谢谢

【问题讨论】:

    标签: angular observable angular2-observables


    【解决方案1】:

    推荐最短形式:

    public getMonths(): Observable<Month[]> {
        return of(this.MONTHS).pipe(
          map(months => months.filter(month => month.id === this.selectedMonth))
        );
      }
    

    【讨论】:

      【解决方案2】:

      问题是你的地图功能。您的 map 函数正在执行一些操作,但不返回任何对象。你必须返回一个对象:

      map(months => {
        let filteredM = months.filter(month => {
          month.id === this.selectedMonth;
        });
        return filteredM;
      })
      

      但是 map 函数的作用域是改变详细源的类型,在这种情况下源和结果具有相同的类型,所以在这种情况下你可以只使用过滤函数而不使用 map。

      【讨论】:

        【解决方案3】:

        这是因为您返回的不是过滤后的数组,而是原始数组。

        public getMonths(): Observable<Month[]> {
            return of(this.MONTHS).pipe(
              map(months => {
                return months.filter(month => month.id === this.selectedMonth);
              })
            );
          }
        

        【讨论】:

        • 抱歉,我的回答有误,因为我忘记返回 map 中的过滤月份。这现在有效。尝试使用您的 StackBlizt 设置。
        猜你喜欢
        • 2018-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-08
        • 1970-01-01
        • 1970-01-01
        • 2017-10-13
        • 1970-01-01
        相关资源
        最近更新 更多