Angular2 Base64 清理不安全的 URL 值

标签 angular

我的服务器的响应如下所示:

[{"coreGoalId":1,"title":"Core goal 1","infrastructure":"Sample Infrastructure","audience":"People","subGoals":null,"benefits":[{"benefitId":1,"what":"string","coreGoalId":1}],"effects":null,"steps":null,"images":[{"imagelId":1,"base64":"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcU\nFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgo\nKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wgARCAIWAe4DASIA\nAhEBAxEB/8QAHAABAAIDAQEB"}]}]

我正在尝试显示其中返回的 base64 图像。

在我的组件中:

ngOnInit() {

    this.homeService.getGoals()
    .subscribe(
        goals => this.coreGoals = goals,
        error =>  this.errorMessage = <any>error);
}

然后在模板中:

<ul>
    <li *ngFor="let goal of coreGoals">
        {{goal.title}}
        <img [src]="'data:image/jpg;base64,'+goal.images[0].base64 | safeHtml" />
    </li>
</ul> 

safeHtml 是我创建的管道,如下所示:

import { Pipe } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({name: 'safeHtml'})
export class SafeHtml {
  constructor(private sanitizer:DomSanitizer){}

  transform(html) {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}

这给了我 Required a safe URL, got a HTML错误。这里出了什么问题?如果我从 <img /> 中移除管道然后它说不安全的网址。

最佳答案

你需要

bypassSecurityTrustResourceUrl(html);

代替

bypassSecurityTrustHtml(html);

关于Angular2 Base64 清理不安全的 URL 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43141534/

相关文章:

angular - 在 angular2 中访问 native 元素的正确方法是什么(2 种不同的方式)文档很少

asp.net-mvc - MVC Web API Angular App ('http://localhost:4200' 已被 CORS 策略阻止)

angular - 来回改变路线后可观察到的数据消失了

angular - 在 Angular 中更改 *ngFor 中的类

angular - 使用 ng-content 将一个组件导入到另一个组件中

JavaScript ECMAScript 6 - 错误 : "You can only use decorators on an export when exporting a class"

javascript - typescript TS7015 : Element implicitly has an 'any' type because index expression is not of type 'number'

angular - Angular 表单绑定(bind)时强制值类型

angular - 是什么导致可观察到的返回结果和在浏览器中显示结果之间的滞后?

angular - 为什么全局错误处理程序中的 toastr 服务在 Angular 4/5/6 中不起作用?