无法在使用typescript的可观察对象列表中使用筛选器



尝试过滤Observable list中的对象列表。

型号:

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

值:

描述:";一月";id:";01〃;

描述:";二月";id:";02〃;

描述:";三月";id:";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

有什么帮助吗?

感谢

建议使用最短的形式:

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

问题在于yout-map函数。您的map函数正在执行一些操作,但没有返回任何对象。你必须返回一个对象:

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

但是map函数的作用域是更改详细描述的源的类型,在这种情况下,源和结果具有相同的类型,因此在这种情况中,您可以只使用filter函数而不使用map。

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

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

最新更新