angular6 - ngOnInIt and array sorting in angular 6 application
问题描述
I have angular 6 application, there in I have below code as per angular project.
ngOnInit() {
this.LoadList("user");
this.listName.sort((a:any,b:any) => {
return a.name < b.name;
})
return this.listName;
}
onFocus() {
this.showSearchResult = true;
}
LoadList(listType:string) {
this.myService.dataList(listType).pipe(takeUntil(this.destroy$))
.subscribe(data => {
if(data.users)
this.response=data.users.;
if(this.response) {
for(let data of this.response) {
this.listName.push({name: data.name, description:data.description})
}
}
this.ref.detectChanges();
});
Here you see that list is not getting alphabetically sroted (ascending), please help me
解决方案
首先,
您的loadList
方法调用服务,我认为这是异步的。所以你必须做这样的事情来进行排序(参见 sortList 函数)
另请注意,在对字符串进行排序时,必须使用小写字母,因为大写字母可能会返回不必要的结果
ngOnInit() {
this.LoadList("user");
}
sortList() {
this.listName.sort((a,b) => {
const nameA = a.name.toLowerCase();
const nameB = b.name.toLowerCase();
if (nameA < nameB) return -1;
if(nameA > nameB) return 1;
return 0;
})
}
onFocus() {
this.showSearchResult = true;
}
LoadList(listType:string) {
this.myService.dataList(listType).pipe(takeUntil(this.destroy$))
.subscribe(data => {
if(data.users)
this.response=data.users.;
if(this.response) {
for(let data of this.response) {
this.listName.push({name: data.name, description:data.description})
}
this.sortList();
}
this.ref.detectChanges();
});
我不知道你的实际代码,但上面的代码导致升序检查这个
var list = [{id: 10, name:'kenny'}, {id:20, name: 'abhi'}, {id: 30, name: 'c'}, {id: 40, name: 'ka'}, {id: 40, name: 'abha'}]
list.sort((a,b) => {
const nameA = a.name.toLowerCase();
const nameB = b.name.toLowerCase();
if (nameA < nameB) return -1;
if(nameA > nameB) return 1;
return 0;
})
console.log(list)
推荐阅读
- javascript - React Native 世博相机风景视频
- solr - 当我使用 nutch 抓取网站时,我丢失了一些 URL
- java - java - 如何在java中使用ArrayList使用递归实现归并排序?
- python - SQL注入攻击:SQL语句中的f-string
- python - 如何更改我的代码以添加删除频道中所有消息的命令?
- python - 过滤0的嵌套列表
- python - 在 Python 中使用带有私钥的 Openssl 签名 Python
- javascript - 如何在单页应用程序网站(例如 React 网站)上安装 Hotjar 以及如何为用户属性安装片段?
- magento - 在 Magento 市场上添加扩展
- c# - 在保持顺序的同时将 NN 组中的项目分组