我正在尝试向我的角度应用程序添加'order by'功能。
我一直在尝试:
<div *ngFor = "let movie of webService.movie_list | async | orderBy:'Year'">
而且我一直在浏览器中收到此错误:找不到管道“ orderBy”
任何帮助将不胜感激。谢谢。
默认情况下,Angular 2.x +中存在No FilterPipe or OrderByPipe,这可能会影响性能。从documentation:
Angular不提供用于过滤或排序列表的管道。熟悉AngularJS的开发人员将其称为filter和orderBy。Angular中没有等效项。
这不是疏忽。 Angular不提供此类管道,因为它们表现不佳,并防止过度缩小。过滤器和orderBy需要引用对象属性的参数。较早在此页面中,您了解到此类管道一定是不纯的,并且几乎在每个更改检测周期中,角度调用都不纯管道。
过滤,尤其是分类是昂贵的操作。用户即使是中等大小的列表,体验也会严重恶化Angular每秒多次调用这些管道方法。过滤和AngularJS应用经常滥用orderBy,从而导致抱怨Angular本身很慢。该指控在间接感觉AngularJS通过以下方式准备了此性能陷阱首先提供filter和orderBy。
相反,只需结合使用RxJS和Array.prototype.sort()来对组件中的数据进行排序/排序:
Component:
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
name = "Angular";
movies$: Observable<Movie[]>;
ngOnInit() {
// Create observable of fake data for demo purposes
// Use rxjs/operators map to sort the data in ascending order
this.movies$ = of(data).pipe(
// You can even extract this operation to a separate function to re-use
map(movies => movies.sort((a, b) => a.Year - b.Year))
);
}
}
模板:
<ul>
<li *ngFor="let movie of movies$ | async">{{movie | json}}</li>
</ul>
只要有可观察的流数据进入组件,只要应用RxJS映射运算符就可以按照所需的方向对数据进行排序。
这里是一个正在运行的example。
希望有帮助!
您必须将pipe
导入模块并在NgModule
声明中声明
import { OrderByPipe } from './order-by.pipe';
@NgModule({
declarations: [ OrderByPipe ]
})