首页 > 解决方案 > 预期的操作数是字符串或数字类型

问题描述

我在角度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);
   });

为什么我不能在我的表格中渲染图像,虽然我的控制台没有错误,但我在文本编辑器中收到错误“预期的操作数是字符串或数字类型”

标签: angular

解决方案


演示示例使用管道为图像制作安全您可以使用下面的管道

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'" /> 

推荐阅读