我有一个Angular组件,它使用service.getItems
从服务中获取数据。有时,服务调用是简单的,在其他情况下,需要一个过滤器。可以通过零部件特性filter
设置此过滤器。
我确信我从根本上遗漏了一些东西,但我不能让它正常工作。我可以让它接受筛选器,或者忽略筛选器,但不会对筛选器的存在做出反应。
有什么建议可以修改下面的代码来实际工作吗?
@Component({}
selector: 'my-component',
template: `
<!-- Items are shown async -->
{{ items | async }}
`
})
export class MyComponent {
//////////////////////////////////////////////////////////////////
// Initialize the filter observable with a null value
//////////////////////////////////////////////////////////////////
constructor(private service) {
this.filter = null;
}
//////////////////////////////////////////////////////////////////
// Filter observable to hookup the filter value to the service
//////////////////////////////////////////////////////////////////
filter$: Subject<Filter> = new Subject<Filter>();
//////////////////////////////////////////////////////////////////
// Service call to fetch items
//////////////////////////////////////////////////////////////////
items$: Observable<any[]> = this.filters$.pipe(
switchMap(filter => this.service.getItems(filter));
);
//////////////////////////////////////////////////////////////////
// Allow filter with
// <my-component [filter]="myFilter">
//////////////////////////////////////////////////////////////////
@Input()
set filter(filter: Filter) {
this.filter$.next(filter);
}
}
https://stackoverflow.com/questions/50823818
复制相似问题