angular 6 应用程序中的 ngOnInIt 和数组排序

ngOnInIt and array sorting in angular 6 application

我有 angular 6 个应用程序,根据 angular 项目,我有以下代码。

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(); 
      });

在这里你看到列表没有按字母顺序排序(升序),请帮助我

首先,

您的 loadList 方法调用了一个服务,我认为这是异步的。所以你必须做这样的事情来排序(见 sortList 函数)

另请注意,在对字符串进行排序时,小写字母是必要的,因为大写字母可能 return 不必要的结果

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)