Created
September 2, 2017 04:07
-
-
Save tonkla/e6692fb2e3ed98ba5dd64675922e180a to your computer and use it in GitHub Desktop.
httpSrc.directive.ts
This file contains hidden or 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 { Directive, ElementRef, Input, OnInit } from '@angular/core'; | |
import { Http, Headers, RequestOptionsArgs, ResponseContentType } from '@angular/http'; | |
import { AuthenticationService } from '../services'; | |
@Directive({ selector: '[httpSrc]' }) | |
export class HttpSrcDirective implements OnInit { | |
@Input('httpSrc') url: string; | |
constructor(private el: ElementRef, private http: Http, private authService: AuthenticationService) {} | |
ngOnInit() { | |
this.authService.getAccessToken().subscribe(token => { | |
if (this.url && token.length > 0) { | |
if (this.url.indexOf('data:') === 0) { | |
// Note: this.url is a data URI like "data:image/jpeg;base64..." | |
this.el.nativeElement.src = this.url; | |
} else { | |
const headers = new Headers({ | |
'Content-Type': this.getContentType(this.url), | |
'X-Authorization': token | |
}); | |
const options: RequestOptionsArgs = { headers: headers, responseType: ResponseContentType.ArrayBuffer }; | |
this.http.get(this.url, options).subscribe(res => { | |
this.el.nativeElement.src = URL.createObjectURL(res.blob()); | |
}); | |
} | |
} | |
}); | |
} | |
private getContentType(url: string): string { | |
let contentType: string; | |
const parts = url.split('.'); | |
const type = parts[parts.length - 1]; | |
switch (type) { | |
case 'jpg': | |
contentType = 'image/jpeg'; | |
break; | |
case 'pdf': | |
contentType = 'application/pdf'; | |
break; | |
default: | |
contentType = `image/${type}`; | |
} | |
return contentType; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment