【发布时间】:2020-06-09 01:22:40
【问题描述】:
我正在尝试优化速度(恰好使我的代码更快)。如何优化下面的代码,以便进一步优化加载时间。如果可能的话,请建议我通常应该记住的内容。 截至目前完成时间 = 2.45 秒。
TS
export class AppComponent implements OnInit {
searchKeywords: string;
CoffeeItemList: any = [];
type: string;
search: string;
selectedType = '';
showLoader: boolean;
empty = false;
data: any = [];
// tslint:disable-next-line:max-line-length
constructor(private getDataListingService: DataListingService) {}
ngOnInit(): void {
this.getGlobalSearchList('');
this.getAllData();
this.getSmartSearchValues('');
if (this.CoffeeItemList.length === 0) {
this.empty = true;
}
}
getAllData() {
this.showLoader = true;
this.getDataListingService.getAllDataLists().subscribe(value => {
this.CoffeeItemList = value.data;
this.showLoader = false;
});
}
getGlobalSearchList(type: string) {
this.selectedType = type;
this.CoffeeItemList = [];
this.getDataListingService.getAllDataLists().subscribe(value => {
this.data = value.data;
console.log(this.data);
// tslint:disable-next-line:prefer-for-of
for (let i = 0; i < this.data.length; i++) {
if (this.data[i].type === type) {
this.CoffeeItemList.push(this.data[i]);
}
}
});
}
getSmartSearchValues(search: string) {
if (search === '' ) {
this.getAllData();
return false;
}
if (search.length >= 3) {
this.getDataListingService.searchList(search).subscribe(value => {
this.data = value.data;
this.CoffeeItemList = value.data;
// check selected type either coffee, mobile or ALL.
if (this.selectedType && this.selectedType !== '' ) {
this.CoffeeItemList = [];
// tslint:disable-next-line:prefer-for-of
for (let i = 0; i < this.data.length; i++) {
if (this.data[i].type === this.selectedType) {
this.CoffeeItemList.push(this.data[i]);
}
}
}
});
}
}
}
【问题讨论】:
-
您的 API 调用将在这里增加很多延迟。如果您想专注于提高 Angular 的效率,请以受控模拟而不是可变请求为基准。
-
您的
getSmartSearchValues(search: string)将在每个键上被调用,而不是您可以在用户停止键入时执行类似操作,它将搜索和过滤数据,因此它将避免searchList的额外API 调用。参考这个blog.sodhanalibrary.com/2016/10/… -
另外,您目前在可观察对象之外的
ngOnInit中检查this.CoffeeItemList.length,因此检查时可能未定义。 -
@hrdkisback 我们怎么知道每次按键都会调用它?
-
@KurtHamilton stackoverflow.com/questions/60262481/… ;)
标签: javascript arrays angular typescript loops