gpt4 book ai didi

加载图像时 Angular 4 空调用

转载 作者:太空狗 更新时间:2023-10-29 17:34:39 26 4
gpt4 key购买 nike

在我的 Angular 4 应用程序中,我必须加载缩略图,所以我有 img [src] 标签。为了在加载此图像的请求中附加授权 token ,我使用了自定义图像管道和异步管道。它运行良好,但如果我在网络选项卡中看到,我可以看到对 null 的奇怪调用,我认为是异步管道:

Request URL:http://localhost:4200/null

image.pipe

@Pipe({name: 'image'})
export class ImagePipe implements PipeTransform {
constructor(private http: Http) {}

transform(url: string, selfLink?: any, width?: any) {
/* tell that XHR is going to receive an image as response, so it can be then converted to blob,
* and also provide your token in a way that your server expects */

if (selfLink) {
url = selfLink + url + width;
}


const headers = new Headers({'Authorization': 'Bearer ' + localStorage.getItem('token'), 'Content-Type': 'image/jpeg'});
// specify that response should be treated as blob data
return this.http.get(url, new RequestOptions({headers: headers, responseType: ResponseContentType.Blob}))
.map(response => response.blob()) // take the blob
.switchMap(blob => {
// return new observable which emits a base64 string when blob is converted to base64
return Observable.create(observer => {
const reader = new FileReader();
reader.readAsDataURL(blob); // convert blob to base64
reader.onloadend = function() {
observer.next(reader.result); // emit the base64 string result
}
});
});
}
}

这是component.html

<div class="card-avatar" (click)="openFilePicker()">
<img class="img pointer" [ngStyle]="{'width.px': 130,'height.px': 130}" *ngIf="links.avatar && imageLink" [src]="(imageLink | image) | async" />
<img src="../../assets/img/default-avatar.png" class="img pointer" *ngIf="links.avatar === undefined">
</div>

异步管道似乎调用了 2 次,1 次是正确的,1 次是错误的,我不知道为什么,我的图像链接永远不会为空或未定义,因为如果我在图像管道中打印 url,我始终看到正确的链接。

这是电话:

enter image description here

此外,如果我直接在管道中写入一个链接而不进行任何调用,我仍然有一个 null <img [src]="('http://.....:8080/api/v1/medias/1/download' | image) | async" />

如何解决这个空调用?

最佳答案

尝试使用 [attr.src]=(imageLink | image) | async"相反。

随着 attr.<whatever>语法,null首先阻止添加属性。

示例:https://stackblitz.com/edit/angular-gitter-btxhuh?file=app%2Fapp.component.html

关于加载图像时 Angular 4 空调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48164509/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com