加载图像时的Angular 4 null调用

时间:2018-01-09 08:59:57

标签: angular angular-pipe

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

  

请求网址: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次是corect,1次是有错误的,我不知道为什么,我的图像链接永远不会为null或未定义,因为如果我在图像中打印url我总是看到正确的链接。

这是电话 enter image description here

此外,如果我直接在没有任何调用的情况下将链接写入管道,我仍然有一个空<img [src]="('http://.....:8080/api/v1/medias/1/download' | image) | async" />

如何解决此空调?

2 个答案:

答案 0 :(得分:2)

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

使用attr.<whatever>语法,null会阻止首先添加属性。

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

答案 1 :(得分:1)

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

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

与 iFrame 相同。