angular - 预期的操作数是字符串或数字类型
问题描述
我在角度2中有这个代码:
<tbody>
<tr *ngFor="let item of vehicleHistoryList | slice: (page-1) * pageSize : page * pageSize">
<th scope="row">{{item.plateNumber}}</th>
<td>{{item.entryPlaza}}</td>
<td>{{item.entryLane}}</td>
<td>{{item.entryDtime}}</td>
<td>{{item.exitPlaza}}</td>
<td>{{item.exitDtime}}</td>
<!-- 'data:image/jpg;base64,' -->
<td>
<img [src]="this._sanitizer.bypassSecurityTrustResourceUrl('data:image/jpg;base64,' + item.img)" /> // ====> THIS IS WHERE I GET THE ERROR
</td>
<td>
<button
class="btn btn-sm btn-outline-success btn-round btn-icon"
>
<i class="nc-icon nc-send"></i>
</button>
</td>
</tr>
</tbody>
这就是我在 TS 文件中获取列表的方式
this.ps.getEntryImformation(model).subscribe((ret: VehicleHistory[]) => {
this.ps.setVehicleHistory(ret);
});
为什么我不能在我的表格中渲染图像,虽然我的控制台没有错误,但我在文本编辑器中收到错误“预期的操作数是字符串或数字类型”
解决方案
演示示例使用管道为图像制作安全您可以使用下面的管道
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
@Pipe({
name: 'safe'
})
export class SafePipe implements PipeTransform {
constructor(protected sanitizer: DomSanitizer) {}
public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
switch (type) {
case 'html': return this.sanitizer.bypassSecurityTrustHtml(value);
case 'style': return this.sanitizer.bypassSecurityTrustStyle(value);
case 'script': return this.sanitizer.bypassSecurityTrustScript(value);
case 'url': return this.sanitizer.bypassSecurityTrustUrl(value);
case 'resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value);
default: throw new Error(`Invalid safe type specified: ${type}`);
}
}
}
并显示图像使用管道
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'media'
})
export class MediaPipe implements PipeTransform {
constructor() {}
public transform(img: any){
return 'data:image/jpg;base64,' + img
}
}
在 HTML 中
<img [src]="(item.img | media) | safe : 'url'" />
推荐阅读
- .net - Powershell SaveFileDialog - 弹出两次
- javascript - 在ajax函数之后全局使用变量
- javascript - 由于输入类型搜索出现红色框,无法继续浏览网页,这仅在 IE 中出现,在 chrome 中不出现
- kentico-12 - Kentico 12 Service Pack - MVC 站点仅重定向到管理站点登录页面
- .net - 在 .NET Core 中干燥 Azure 函数应用程序
- python - 正则表达式匹配失败
- ios - 应用程序未在 TestFlight 中显示为 App Store Connect 用户
- c++ - 如何仅使用邻接表在无向图中找到存在的循环(顶点也没有)?
- java - 在 Windows 中运行时,Java 中的 python 脚本子进程不会被破坏
- google-cloud-platform - 对 pubsub 访问令牌的数据流访问