I recently created a custom pipe for the image src in my application:
It is applied to selectors like this:
<img [src]="myobject?.URL | secure" />
Here's the code snippet for the pipe:
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 {
// I am facing an issue here where the image doesn't render
// when transitioning to this else block
return Observable.of(url);
}
}
}
The problem arises when the else part of the condition inside the pipe's code is triggered. It returns an empty response and fails to display the image.
Could you please advise me on how to effectively return the original url specified by "[src]="myobject?.URL" when the else block is executed?