当 angular 绑定的 `` 标签 `src` 值为 `null` 或空字符串时,浏览器会尝试请求 `/null` 路径,从而触发 404 错误;正确做法是条件渲染图片标签,仅在有效 url 存在时才渲染。
在你的代码中,[src]="_sanitizer.bypassSecurityTrustResourceUrl(item.itemValue)" 直接将 item.itemValue(可能为 null、undefined 或空字符串)传入 bypassSecurityTrustResourceUrl,而该方法不会校验输入有效性——它只是绕过 Angular 的安全策略,将原始值转为 SafeResourceUrl。若 item.itemValue 为 null,最终生成的 src 实际为 "null" 字符串,浏览器便发起对 http://your-domain/null 的请求,自然返回 404。
✅ 正确解决方案:避免渲染无效 标签,而非依赖 src 属性兜底。推荐使用 *ngIf 进行前置判断:
<ng-container [ngSwitch]="item.itemTitle" id="container">
<!-- 仅当 item.itemValue 存在且非空时才渲染 img -->
<img class="img thumbnail"
*ngSwitchCase="'Graph1'"
*ngIf="item.itemValue && item.itemValue.trim()"
(click)="openDialogImg(myTemplate)"
[src]="_sanitizer.bypassSecurityTrustResourceUrl(item.itemValue)"
alt="Graph 1"
/>
<img class="img thumbnail"
*ngSwitchCase="'Graph2'"
*ngIf="item.itemValue && item.itemValue.trim()"
(click)="openDialogImg(myTemplate)"
[src]="_sanitizer.bypassSecurityTrustResourceUrl(item.itemValue)"
alt="Graph 2"
/>
<!-- 对应的大图弹窗模板(同样需校验) -->
<ng-template #myTemplate>
<img *ngIf="item.itemValue && item.itemValue.trim()"
[src]="_sanitizer.bypassSecurityTrustResourceUrl(item.itemValue)"
style="height:100%; width:100%">
<button id="x" mat-button (click)="myDialogRef?.close()">X</button>
</ng-template>
<span *ngSwitchDefault>{{ item.itemValue }}</span>
</ng-container>⚠️ 注意事项:
- 不要依赖 onerror 事件动态替换 src(如 onerror="this.src='placeholder.png'"),因其在 Angular 模板中难以与变更检测协同,且存在竞态风险;
- bypassSecurityTrustResourceUrl 仅用于可信的、已校验的 URL(如 base64 数据 URI 或受控后端返回的绝对路径),切勿对未清洗的用户输入调用,否则引入 XSS 风险;
- 若 item.itemValue 可能是 null、undefined、空字符串或仅空白字符,建议统一用 item.itemValue?.trim() 判断;
- 如需展示默认占位图,可在 *ngIf 为 false 时渲染 No image available,保持 UI 一致性。
总结:404 并非 bug,而是浏览器对非法资源路径的标准响应。根本解法是「控制渲染时机」——让 标签只在具备有效、非空、可信 URL 时才进入 DOM,从源头规避无效请求。


















