您可以创建一个带有订阅参数的排序函数并在每次更改查询参数时调用该函数。以下是一个示例:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';
@Component({
selector: 'app-my-component',
template: `
- {{ item }}
`,
})
export class MyComponent implements OnInit {
queryParams$: Observable;
data$: Observable;
sortedData: Observable;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
// get initial data
this.data$ = this.route.data.pipe(map((data) => data.items));
// get query params
this.queryParams$ = this.route.queryParamMap;
// sort data when queryParams change
this.sortedData = this.queryParams$.pipe(
switchMap((params) =>
this.data$.pipe(
map((data) => {
const sortParam = params.get('sort');
if (sortParam === 'ASC') {
return data.sort((a, b) => a.value - b.value);
} else if (sortParam === 'DESC') {
return data.sort((a, b) => b.value - a.value);
} else {
return data;
}
})
)
)
);
}
}
在此示例中,我们使用了 switchMap
操作符来订阅查询参数的更改,并使用 map
操作符来返回一个已排序的数据流。在 map
函数中,我们检查查询参数中的排序参数,并根据不同的排序要求对数据进行重新排序。最后,我们将结果存储在 sortedData
变量中,并在模板中使用 async
管道来订阅数据的异步结果。
上一篇:Angular-在for循环内设置interval函数无法正常工作
下一篇:Angular-在检查后更改表达式导致ExpressionChangedAfterItHasBeenCheckedError错误,不使用observables