我想在img标签中显示一个图像:我这样做
零件
this.file.url=this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(this.file.url));
Run Code Online (Sandbox Code Playgroud)
模板
<img [src]="file.url">
Run Code Online (Sandbox Code Playgroud)
我收到了这个错误
ERROR TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.
Run Code Online (Sandbox Code Playgroud)
Gre*_*nko 12
您应该responseType: ResponseContentType.Blob在GET-Request设置中进行设置,因为这样您可以将图像作为blob获取并在以后转换为base64编码的源.你上面的代码不好.如果您想要正确执行此操作,请创建单独的服务以从API获取图像.因为在组件中调用HTTP-Request并不好.
这是一个工作示例:
创建image.service.ts并放置以下代码:
getImage(imageUrl: string): Observable<File> {
return this.http
.get(imageUrl, { responseType: ResponseContentType.Blob })
.map((res: Response) => res.blob());
}
Run Code Online (Sandbox Code Playgroud)
现在你需要创建一些函数image.component.ts来获取图像并以html显示它.
要从Blob创建图像,您需要使用JavaScript FileReader.这是创建new的函数,FileReader并监听FileReader的load-Event.结果,此函数返回base64编码的图像,您可以在img src-attribute中使用它:
imageToShow: any;
createImageFromBlob(image: Blob) {
let reader = new FileReader();
reader.addEventListener("load", () => {
this.imageToShow = reader.result;
}, false);
if (image) {
reader.readAsDataURL(image);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您有多个图像,则可以定义imageToShow[] = []为数组.现在你可以简单地推reader.result送到这个阵列.例如:this.imageToShow.push(reader.result).在您的模板中,您可以迭代并输出此数组*ngFor="let image of imageToShow;".
现在你应该使用你创建的ImageService来从api获取图像.您应该订阅数据并将此数据提供给createImageFromBlob-function.这是一个示例函数:
getImageFromService() {
this.isImageLoading = true;
this.imageService.getImage(yourImageUrl).subscribe(data => {
this.createImageFromBlob(data);
this.isImageLoading = false;
}, error => {
this.isImageLoading = false;
console.log(error);
});
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以imageToShow在HTML模板中使用-variable,如下所示:
<img [src]="imageToShow"
alt="Place image title"
*ngIf="!isImageLoading; else noImageFound">
<ng-template #noImageFound>
<img src="fallbackImage.png" alt="Fallbackimage">
</ng-template>
Run Code Online (Sandbox Code Playgroud)
我希望这个描述清楚明白,你可以在你的项目中使用它.
| 归档时间: |
|
| 查看次数: |
11620 次 |
| 最近记录: |