Angular4显示来自服务器的图像
我想在img标签中显示图像:
我这样做 零件 this.file.url=this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(this.file.url)); 模板 <img [src]="file.url"> 我收到了这个错误 ERROR TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided. 解决方法
您应该在GET-Request设置中设置responseType:ResponseContentType.Blob,因为这样您可以将图像作为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()); } 现在你需要在image.component.ts中创建一些函数来获取图像并在html中显示它. 要从Blob创建图像,您需要使用JavaScript的FileReader. imageToShow: any; createImageFromBlob(image: Blob) { let reader = new FileReader(); reader.addEventListener("load",() => { this.imageToShow = reader.result; },false); if (image) { reader.readAsDataURL(image); } } 如果您有多个图像,则可以将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); }); } 现在,您可以在HTML模板中使用imageToShow变量,如下所示: <img [src]="imageToShow" alt="Place image title" *ngIf="!isImageLoading; else noImageFound"> <ng-template #noImageFound> <img src="fallbackImage.png" alt="Fallbackimage"> </ng-template> 我希望这个描述清楚明白,你可以在你的项目中使用它. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- shell脚本批量执行命令----不需要判断上一步执行结果
- twitter-bootstrap中“bootstrap”一词的含义
- unix – 我如何知道AIX中的旧操作系统级别?
- scala – sbt – 将非托管资源添加到控制台
- Bootstrap3基础 text-right/left/center 设置标题右对齐、左
- 使用shell脚本监控服务器内存和cpu使用量,自动清理无效内存
- shell – 当找到与sed匹配时替换整行
- cxf WebService整合Spring
- 窗口 – 为什么在Vim中将Esc重新映射到CAP LOCK?
- shell杀死进程, adb server is out of date. killing