Angular 4 加载图像时调用 null

Angular 4 null call when loading image

在我的 angular 4 应用程序中,我必须加载缩略图,所以我有 img [src] 标签。为了在加载此图像的请求中附加授权令牌,我使用了自定义图像管道和异步管道。它运行良好,但如果我在网络选项卡中看到,我可以看到对 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 次是错误的,我不知道为什么,我的图像 link 永远不会为空或未定义,因为如果我打印url 在图像管道中我总是看到正确的 link.

这是电话:

此外,如果我直接将 link 写入管道而不进行任何调用,我仍然有一个空值 <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

问题是 src 属性试图在异步管道解析某些值之前执行 GET 请求。

可以通过使用 *ngIf 并检查您希望在 src 中使用的值是否已解析来解决。

与 iFrame 相同。