我有一个组件,该组件的ngOnInit
订阅了服务中的BehaviorSubject
。该代码为mat-table
设置数据源:
ngOnInit() {
this.citizenService.citizens.subscribe((citizens: Citizen[]) => {
console.log(citizens);
if (citizens.length > 0) {
citizens.forEach(citizen => {
citizen.weekInterval = "Ikke nok";
citizen.weeklyCare.forEach(wc => {
if (wc.hospitalized) {
Object.keys(wc).forEach(key => {
if (key != "weeklyCareIdentifier" && key != "hospitalized") {
wc[key] = null;
}
});
}
});
this.citizenService.calculateCareChange(citizen, false);
})
let citizensWithAlerts: Citizen[] = JSON.parse(JSON.stringify(citizens));
for (let i = citizensWithAlerts.length - 1; i > -1; i--) {
if (!citizensWithAlerts[i].totalCare || !(citizensWithAlerts[i].totalCare >= this.citizenService.alertThreshold)) {
citizensWithAlerts.splice(i, 1);
}
}
citizensWithAlerts = citizensWithAlerts.sort((a, b) => {
if (a.totalCare < b.totalCare) return 1;
if (a.totalCare > b.totalCare) return -1;
return 0;
});
this.citizenWithAlerts = citizensWithAlerts;
this.citizensToPrint = citizensWithAlerts;
this.tableDataSource.data = citizens;
}
});
}
初始化组件后,我的应用程序被阻塞了大约6秒钟,然后出现了带有数据填充表的组件视图。但是,如果我将上述所有代码放在setTimeout(() => {**code**}, 0 );
中,则视图将立即初始化,然后立即填充表。 setTimeout
相差6秒。
为什么会这样,我该如何解决?
此外,当我不用订阅从http调用创建的BehaviorSubject
的{{1}}时,代码也可以正常工作。
答案 0 :(得分:0)
您具有二次复杂度:O(N²)
然后在2d for循环中,您计算一些东西
然后您进行排序。
尝试在内部超时的情况下使用ngAfterViewInit(){},这会有所作为。
还要用一个空数组初始化表。
您的代码如下所示:
import { Component, OnInit, AfterViewInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, AfterViewInit {
constructor(private _citizenService: SitizenService) { }
ngOnInit() { }
ngAfterViewInit() {
this.tableDataSource.data = new DataSource([]);
this.getSitizens();
}
getSitizens() {
this.citizenService.citizens.subscribe((citizens: Citizen[]) => {
console.log(citizens);
// add comments
if (citizens.length > 0) {
citizens.forEach(citizen => {
citizen.weekInterval = "Ikke nok";
citizen.weeklyCare.forEach(wc => {
if (wc.hospitalized) {
Object.keys(wc).forEach(key => {
if (key != "weeklyCareIdentifier" && key != "hospitalized") {
wc[key] = null;
}
});
}
});
this.citizenService.calculateCareChange(citizen, false);
});
// add comments
let citizensWithAlerts: Citizen[] = JSON.parse(JSON.stringify(citizens));
for (let i = citizensWithAlerts.length - 1; i > -1; i--) {
if (!citizensWithAlerts[i].totalCare || !(citizensWithAlerts[i].totalCare >= this.citizenService.alertThreshold)) {
citizensWithAlerts.splice(i, 1);
}
};
// add comments
citizensWithAlerts = citizensWithAlerts.sort((a, b) => {
if (a.totalCare < b.totalCare) return 1;
if (a.totalCare > b.totalCare) return -1;
return 0;
});
// add comments
this.citizenWithAlerts = citizensWithAlerts;
this.citizensToPrint = citizensWithAlerts;
this.tableDataSource.data = citizens;
}
});
}
}
class DataSource {
constructor(private data: any[]){}
}