You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中Iframe加载资源失败时如何显示替代文本

解决Angular 12中iframe加载失败时显示自定义提示的问题

你的代码目前有两个关键问题导致需求没实现,直接修改如下:

1. 修正组件逻辑(display-content.component.ts)

  • 将serverDown改为boolean类型并初始化,确保*ngIf能正确判断显示状态
  • 错误触发时更新serverDown标记
contentUrl: string;
serverDown = false; // 改为boolean类型并初始化

constructor(private sanitizer: DomSanitizer) { }

ngOnInit(): void {
  const url= "http://localhost:5000/getContents";
  this.contentUrl = this.sanitizer.bypassSecurityTrustResourceUrl(url);
}

onIframeError(event) {
  console.log('iframe failed');
  this.serverDown = true; // 触发错误时标记服务器不可用
}

2. 修正模板绑定(display-content.component.html)

  • 把iframe的(load)事件换成(error),确保服务器宕机时触发错误处理
  • 通过*ngIf控制iframe和提示文本的切换显示
<iframe *ngIf="!serverDown" [src]="contentUrl" frameborder="0" class="content" (error)="onIframeError($event)"></iframe>
<p *ngIf="serverDown">Server is down</p>

逻辑说明

当目标服务器宕机时,iframe加载失败会触发(error)事件,调用onIframeError将serverDown设为true。此时模板会自动隐藏iframe,同时显示自定义的"Server is down"提示,替代浏览器默认的连接失败页面。

内容的提问来源于stack exchange,提问作者Asif Zaidi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 05:45:18