Angular 2 - Inject custom headers on iframe Angular 2 - Inject custom headers on iframe angular angular

Angular 2 - Inject custom headers on iframe


You can do it like this:

  1. Create a service that will send http get request along with headers, and expects blob response.
  2. Use that service in your component to set src of an iframe.
  3. Remove [src]="secureSrc" from iframe and leave only #iframe

.

// serviceimport { Injectable } from '@angular/core';import { ResponseContentType, Http, RequestOptions, Headers } from '@angular/http';import { Observable } from 'rxjs/Observable';import { Subscriber } from 'rxjs/Subscriber';@Injectable()export class UrlHelperService {    constructor(private http: Http) {    }    get(url: string): Observable<any> {        let options = new RequestOptions();        options.headers = new Headers();        options.headers.append('AUTH-TOKEN', 'SomeToken123');        options.responseType = ResponseContentType.Blob;        return new Observable((observer: Subscriber<any>) => {            let objectUrl: string = null;            this.http                .get(url, options)                .subscribe(m => {                    objectUrl = URL.createObjectURL(m.blob());                    observer.next(objectUrl);                });            return () => {                if (objectUrl) {                    URL.revokeObjectURL(objectUrl);                    objectUrl = null;                }            };        });    }}// componentimport { Component, ViewChild, OnInit, ElementRef } from '@angular/core';import { UrlHelperService } from './url-helper.service';  @Component({  selector: '',  templateUrl: './my-app.component.html'})   export class MyAppComponent implements OnInit {  @ViewChild('iframe') iframe: ElementRef;  constructor(private urlHelperService: UrlHelperService) { }  ngOnInit() {    this.urlHelperService.get('http://localhost/api/file/123')      .subscribe(blob => this.iframe.nativeElement.src = blob);  }}