[英]ExpressionChangedAfterItHasBeenCheckedError on ngOnInit with Promise
I'm trying to achieve something pretty simple: 我正在努力实现一些非常简单的事情:
Display data given by a service in my component. 显示我的组件中的服务给出的数据。
So here is what I have that used to work: 以下是我以前的工作:
In my component: 在我的组件中:
...
dataSet: String[];
ngOnInit(){
this._service.getDataId().then(data => this.dataSet = data);
}
...
In my service: 在我的服务中:
...
getDataId(){
return this.http.get(adress).toPromise()
.then(response => response.json() as String[])
.catch(this.handleError);
} // return a Promise<String[]>
...
In the view: 在视图中:
...
<ul>
<li *ngFor="let data of dataset">
{{ data['id'] }}
</li>
</ul>
...
But now , I've changed the service function to get more data. 但是现在 ,我已经改变了服务功能以获得更多数据。
I get an ExpressionChangedAfterItHasBeenCheckedError since then. 从那时起我得到一个ExpressionChangedAfterItHasBeenCheckedError 。
Here is the change in the service: 以下是服务的变化:
...
getMoreData() {
const result: Map<string, String[]> = new Map();
return this.http.get(this.adress).toPromise()
.then((response) => {
return Promise.all(Array.from(response.json())
.map(id => {
return this.http.get(this.adress + '/' + id').toPromise()
.then((rep) => {
result.set(domain['@href'], rep.json() as String[]);
}).catch(this.handleError)
})
);
})
.then(() => result)
.catch(this.handleError);
} // return a Promise<Map<string, String[]>>
...
This raise an error even if the data is correctly displayed. 即使数据正确显示,也会引发错误。
I've tried a few workaround (setTimeout, ChangeDetectorRef) but I don't even know why this was working and is not anymore since both functions are returning a Promise<Stuff>
. 我已经尝试了一些解决方法(setTimeout,ChangeDetectorRef),但我甚至不知道为什么这个工作并且不再存在,因为两个函数都返回了Promise<Stuff>
。
I'm also aware that I need to initialize my attribute like this in the component to avoid the null error when the view is loading: 我也知道我需要在组件中初始化我的属性,以避免在加载视图时出现null错误:
this.moreData: Map<string, String[]> = new Map();
And this might also cause my issue, but how am I supposed to do then ? 这也可能导致我的问题,但我该怎么办呢?
--- ---
Project using 项目使用
Angular 4.2.2 Angular 4.2.2
Typescript 2.3.4 打字稿2.3.4
In fact, this is related with this issue: https://github.com/angular/angular/issues/17725 实际上,这与此问题有关: https : //github.com/angular/angular/issues/17725
The Map<> structure is here the problem since it creates a new Iterator every time when you use it in your view (ex: when using .entries) Map <>结构就是问题,因为每次在视图中使用时都会创建一个新的Iterator(例如:使用.entries时)
A workaround can be found in the link above. 可以在上面的链接中找到解决方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.