gpt4 book ai didi

angular - http.get 太慢,更改检测未注册更改

转载 作者:行者123 更新时间:2023-12-04 03:05:39 24 4
gpt4 key购买 nike

我正在构建一个日历应用程序,它使用 http.get 从后端获取特定日期的信息(目前后端是一个服务器模拟)。我的问题是异步 http.get 的速度不够快,无法在页面呈现期间传送数据,而且数据到达后也不会以某种方式显示,我相信变化检测应该可以正常检测到这一点。关于 http.get 方法,我遵循了 Angular.io 上的示例,可在此处找到 https://angular.io/guide/http#subscribe

代码:

获取服务:

getDayInfo(date: string): Observable<any> {
return this.http.get(url)
.map(this.extractData)
.catch(this.handleError);
}

private extractData(res: Response) {
let body = res.json();
return body; // not really doing much with the data here yet
}

组件.ts:

dayData: any[];
dayInfo: any[];

constructor(private fetcher: FetchService) {}

ngOnInit(): void {
this.getDay();
setTimeout(() => { this.setDayData(); }, 10);
// the setTimeout is mostly here for testing, tried to sort of set the
// Data after the async http.get was done
}

getDay () {
this.fetcher.getDayInfo(this.date).subscribe(
body => this.dayInfo = body,
);
}

setDayData() {
if (this.dayInfo) {
this.dayData = this.dayInfo;
console.log(this.dayData);
// and some more things that only matter for some CSS markup
}
}

组件.html:

<!--{{ dayInfo[0].type.name }}-->
<div *ngIf="dayData">
<div *ngFor="let data of dayData">
<p>{{ data.type.name }}</p>
</div>
</div>
<div *ngIf="!dayData">
<p>Loading</p>
</div>

每天总是只显示加载,超时后,控制台填充实际和适当的 dayData,站点仍然只显示加载。如果我在 html 中的 {{ dayInfo[0].type.name }} 中发表评论,我首先得到几天的“加载”和一个控制台错误说 dayInfo 未定义,然后一点一点地,日子填满,显示正在加载和我想要的数据,尽管控制台充满了如上所述的错误。

现在,由于我无法加速异步 http.get,有没有办法触发更改检测以获取 dayData 中的更改?或者任何其他让我显示正确数据的解决方法?

PS:当控制台记录 setDayData 中的 dayData 时,我注意到的另一件事是有时日志不会列出所有日期,这意味着它可能会显示一个月的前 27 天,但没有关于其余日期的日志条目。不确定是什么原因造成的。


编辑:在第一个评论和第一个答案之后,我将 component.ts 中的 getDay 方法更改为:

getDay () {
this.fetcher.getDayInfo(this.date).subscribe(
body => {
this.dayInfo = body;
this.setDayData();
);
}

现在,我在上面“PS:”中描述的奇怪行为已经消失,所有日期都显示在日志中,尽管它们是混合的(不再按时间顺序排列)。网站仍然只显示“正在加载”,但不会更新到正确的数据。我可能需要在此处手动触发更改检测或其他操作。

最佳答案

您的超时可能在您获取数据之前触发。您可能不想从 ngOnInit 调用 setDayData,而是从 getDayInfo 订阅 block 的主体调用它。

这将确保您拥有数据并在收到数据后调用后续方法。

ngOnInit(): void {
this.getDay();
}

getDay () {
this.fetcher.getDayInfo(this.date).subscribe(
body => {
this.dayInfo = body;
this.setDatData();
}
);
}

至于另一个关于未定义的问题——那是因为当模板第一次显示时你有一个空数组(它直到你的 setDayData 方法运行时才被设置)。如果你真的想要在屏幕上显示,你也可以将它包装在 ngIf 中。这样您就知道那里也有数据。

关于angular - http.get 太慢,更改检测未注册更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44802175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com