首页 > 解决方案 > 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

标签: angular6

解决方案


首先,

您的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)


推荐阅读