Observable.of return 图像 src 中的管道没有任何内容

Observable.of return nothing for pipe in image src

我在我的应用程序中为图像 src 创建了一个自定义管道:

它在这样的选择器上使用:

<img [src]="myobject?.URL | secure" />

管道的代码是:

    import { Pipe, PipeTransform } from '@angular/core';
    import { Http, ResponseContentType } from '@angular/http';
    import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/observable/of';

    @Pipe({
      name: 'secure'
    })
    export class SecurePipe implements PipeTransform {

      constructor(private http: Http, private sanitizer: DomSanitizer) { }

      transform(url): Observable<SafeUrl> {

        if (//myboolcondition) {
          return this.http
            .get(url, { responseType: ResponseContentType.Blob })
            .catch(err => Observable.throw(err))
            .map(val => this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(val)));
        }
        else {
          // This is not working and the image src are blank 
// My goal in this else loop is just to return what was there originally // in [src]="myobject?.URL in selector

          return Observable.of(url);

        }
      }
    }

我面临的问题是管道代码中 if 循环的 else 部分不工作并且 returning 空响应和else 部分未呈现图像。

你能告诉我如何 return 与 url 相同的 "[src]="myobject?.URL"else 在我的代码中满足条件循环。

您正在返回一个 Observable,而一个 Observable 实例仅在您 subscribe 时才开始发布值。 如果您想在模板中直接使用 observables,则需要 AsyncPipe

AsyncPipe accepts as an argument an observable or a promise, calls subscribe or attaches a then handler, then waits for the asynchronous result before passing it through to the caller.

修改后的代码

  <img [src]="myobject?.URL | secure | async" />