2017-03-31 49 views
11

響應看起來像以下:Angular2的Base64消毒不安全的URL值從我的服務器

[{"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 />刪除管道,則表示不安全的網址。

回答

17

您需要

bypassSecurityTrustResourceUrl(html); 

,而不是

bypassSecurityTrustHtml(html); 
+0

謝謝!那是我的錯誤。 – Nitish