我正在为我的 Angular 应用程序创建一个加载器。
最常见的方法是在订阅 http 请求时传递布尔参数,但我的服务的响应是一系列图像 URL,因为页面充满了图像。
因此,当检索到 URL 时加载程序停止,但由于连接速度慢,用户会因为图像尚未完成加载而感到恼火。
我曾尝试使用 Javascript 的加载事件来监听我的资源何时完成加载,以便我可以在那时停止加载程序,但似乎我无法从监听器函数中操作加载程序的值。
这是我尝试过的:
//the TS component
isLoading: boolean;
ngOnInit() {
this.isLoading = true;
this.checkIfLoaded();
}
checkIfLoaded() {
window.addEventListener("load", function (event) {
console.log("All resources finished loading!");
//here i should do something, either returning false or...
//...manipulating the isLoading, but i can't access isLoading from here
});
}
//the template
<ng-container *ngIf="isLoading">
<app-spinner></app-spinner>
</ng-container>
环境:Angular 4.4 非常感谢任何帮助,谢谢
原文由 hzbarkan 发布,翻译遵循 CC BY-SA 4.0 许可协议
只需使您的组件实施
AfterViewInit
false
设置ngAfterViewInit()
isLoading
无需附加额外的事件处理程序,angular 完全覆盖了它的生命周期回调。