如何有效地检查 Angular 2 中加载的数据?成分?
在Angular中,我在我的每个组件中进行以下操作,这些组件与API通信:
export class ExampleComponent implements OnInit {
public datasLoaded: boolean = false;
private datasALoaded: boolean = false;
private datasBLoaded: boolean = false;
private datasCLoaded: boolean = false;
constructor(private api: MyAPIService) { }
ngOnInit(): void {
fetchDatas();
}
fetchDatas() {
this.api.getDatasA().subscribe({
next: datas => {
this.datasALoaded = true;
this.checkDatasLoaded();
}
});
this.api.getDatasB().subscribe({
next: datas => {
this.datasBLoaded = true;
this.checkDatasLoaded();
}
});
this.api.getDatasC().subscribe({
next: datas => {
this.datasCLoaded = true;
this.checkDatasLoaded();
}
});
}
private checkDatasLoaded() {
this.datasLoaded = this.datasALoaded && this.datasBLoaded && this.datasCLoaded;
}
}
我对代表其状态的每个请求都有一个变量(是否加载)。和模板中使用的公共变量datasloaded
仅在加载所有内容时才汇总所有请求的状态并显示内容:
<div *ngIf="datasLoaded"></div>
这很好,但是为每个组件写作很痛苦。显然,每个组件都是不同的,不是相同的请求,而不是相同数量的请求,而在加载数据或不加载数据时的行为不是相同的行为,但是我正在寻找更容易编写的解决方案。
您如何处理这种情况?
In angular i do the following in each of my component which communicate with an API :
export class ExampleComponent implements OnInit {
public datasLoaded: boolean = false;
private datasALoaded: boolean = false;
private datasBLoaded: boolean = false;
private datasCLoaded: boolean = false;
constructor(private api: MyAPIService) { }
ngOnInit(): void {
fetchDatas();
}
fetchDatas() {
this.api.getDatasA().subscribe({
next: datas => {
this.datasALoaded = true;
this.checkDatasLoaded();
}
});
this.api.getDatasB().subscribe({
next: datas => {
this.datasBLoaded = true;
this.checkDatasLoaded();
}
});
this.api.getDatasC().subscribe({
next: datas => {
this.datasCLoaded = true;
this.checkDatasLoaded();
}
});
}
private checkDatasLoaded() {
this.datasLoaded = this.datasALoaded && this.datasBLoaded && this.datasCLoaded;
}
}
I have a variable for each request representing its status (loaded or not). And a public variable datasLoaded
used in the template to aggregate the status of all requests and display content only if everything is loaded :
<div *ngIf="datasLoaded"></div>
That's working perfectly fine , but it's a pain to write for each component. Obviously every components are different , not the same requests , not the same number of requests , not the same behaviour when datas are loaded or not but i'm looking for a solution a bit more easy to write.
How do you handle this scenario ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将不会克服“数据载”标志,但是您可以尝试缩短代码,甚至可以用
forkjoin
作为实用程序进行操作。You will not overcome 'datasLoaded' flag, but you could try to shorten the code or even do it as an utility with
forkJoin