我这样解决了这个问题。
假设您有一个容器news-list.component.ts 和ngOnInit。它将当前的 queryParams 保存在 currentFilters 中,如果没有它们,则发出简单的 GET 请求,否则发出 POST 请求。
ngOnInit() {
this.route.queryParams.subscribe(queryParams => {
if (!!queryParams) {
this.currentFilters = <NewsFilter>{...queryParams, offset: 0, size: 6};
this.news$ = this.newsPostsService.getNewsByFilter(this.currentFilters);
} else {
this.news$ = this.newsPostsService.getMainNews();
}
});
}
然后创建一个组件<news-rubric></news-rubric>,它具有以下视图。你经过currentFilters 并取走rubricClick,然后处理它。
news-list.component.html
<ml-news-rubrics [currentFilters]="currentFilters"
(rubricClicked)="onRubricFilter($event)"
></ml-news-rubrics>
news-list.component.ts
onRubricFilter(filters: NewsFilter) {
this.currentFilters = {...filters};
this.router.navigate([], {queryParams: filters, relativeTo: this.route});
}
然后在news-rubric.component.ts 中执行如下操作:
onRubricClicked(rubricId: string) {
// check if filter exists and if not then put ID in filter
if (!this.currentFilters.filterByAnyRubricIds) {
this.putIdInFilter('filterByAnyRubricIds', rubricId, this.currentFilters.filterByAnyRubricIds);
} else {
// check if clicked ID is not in filter. put in filter
if (!this.currentFilters.filterByAnyRubricIds.includes(rubricId)) {
this.putIdInFilter('filterByAnyRubricIds', rubricId, this.currentFilters.filterByAnyRubricIds);
} else {
// if ID in filter remove it from filter
this.removeIdFromFilter('filterByAnyRubricIds', rubricId, this.currentFilters.filterByAnyRubricIds);
}
}
this.rubricClicked.emit(this.currentFilters);
}
有最棘手的代码。它通过使用过滤后的 ID 更新其 key 来创建新过滤器。
private putIdInFilter(key: string, value: any, list: any) {
if (!list || !(list instanceof Array)) {
if (!list) {
this.currentFilters = {...this.currentFilters, [key]: [value]};
} else {
this.currentFilters = {...this.currentFilters, [key]: [this.currentFilters[key], value]};
}
} else {
this.currentFilters = {...this.currentFilters, [key]: [...this.currentFilters[key], value]};
}
}
private removeIdFromFilter(key: string, value: any, list: any) {
if (!list || !(list instanceof Array)) {
this.currentFilters = <NewsFilter>{
...this.currentFilters, [key]: null
};
return;
}
const filteredValues = [...list.filter(i => i !== value)];
if (filteredValues.length > 0) {
this.currentFilters = <NewsFilter>{
...this.currentFilters, [key]: filteredValues
};
} else {
delete this.currentFilters[key];
}
}
而NewsFilter 只是类似于QueryParams 的接口,带有需要过滤的键。