我在我的应用程序中为图像 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 部分不起作用,并且返回空响应,并且图像没有为 else 渲染 部分。
你能让我知道当条件的 else 循环时如何返回与 "[src]="myobject?.URL" 相同的 url在我的代码中满足了。
最佳答案
您正在返回一个 Observable
,并且 Observable
实例仅在您订阅
时才开始发布值。
如果您想直接在模板中使用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" />
关于javascript - Observable.of 对图像 src 中的管道不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51029809/