Created
November 28, 2017 11:28
-
-
Save Armenvardanyan95/1814c66f1f90becde70cb65f6170939f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Pipe, PipeTransform } from '@angular/core'; | |
import { Http, RequestOptions, Headers, ResponseContentType } from @angular/http'; | |
import { Observable } from 'rxjs/Observable'; | |
import 'rxjs/add/operator/map'; | |
import 'rxjs/add/operator/switchMap'; | |
@Pipe({name: 'image'}) | |
export class ImagePipe implements PipeTransform { | |
constructor(private http: Http) {} | |
transform(url: string) { | |
const headers = new Headers({'Authorization': 'MY TOKEN', 'Content-Type': 'image/*'}); /* 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 */ | |
return this.http.get(url, new RequestOptions({headers: headers, responseType: ResponseContentType.Blob})) // specify that response should be treated as blob data | |
.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 | |
} | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment