Angular 2 - Inject custom headers on iframe - javascript

I'm getting crazy trying to inject request custom header (something like 'AUTH-TOKEN':'SomeToken123') to an on Angular 4.
I need to pass to the iframe page some required custom header parameters.
Anyone can please help me?
foo.component.html
<iframe [hidden]="isLoading" class="full" #iframe [src]="secureSrc" (load)="onIframeLoad()" frameborder="0" ></iframe>
component.ts
#Component({
selector: 'app-foo',
templateUrl: './foo.component.html'
})
export class FooComponent implements OnInit {
#ViewChild('iframe') iframe: ElementRef;
public isLoading: Boolean;
public secureSrc: SafeResourceUrl;
constructor(
private sanitizer: DomSanitizer,
private renderer: Renderer2,
private router: Router
) { }
public ngOnInit() {
this.isLoading = true;
this.secureSrc = this.getIframeURL();
}
private getIframeURL(): SafeResourceUrl {
return this.sanitizer
.bypassSecurityTrustResourceUrl('https://iframe.address');
}
public onIframeLoad(): void {
if (typeof this.iframe !== 'undefined') {
// Once iFrame Loaded
if (typeof this.token !== 'undefined') {
this.iframe
.nativeElement
.contentWindow
.postMessage({
externalCommand: 'some-action',
parameter : 'action parameter'
}, '*');
}
this.isLoading = false;
}
}
}
Thank you!

You can do it like this:
Create a service that will send http get request along with headers,
and expects blob response.
Use that service in your component to set src of an iframe.
Remove [src]="secureSrc" from iframe and leave only #iframe
.
// service
import { 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;
}
};
});
}
}
// component
import { 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);
}
}

Related

Angular 6 : Issue of component data binding

I call service which make http call, I assign response to component variable now when I try access that component variable to view it display blank.
Means component variable assign in subscribe successfully but cant acceess in html view.
I think view is loaded before values assign to component data.
component
import {Component, OnInit, ChangeDetectionStrategy} from '#angular/core';
import { UserService } from '../../../../../core/services/users/user.service';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'm-user-list',
templateUrl: './user-list.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserListComponent implements OnInit {
list;
roles = {};
current_page: any
totalRecords: any
public showContent: boolean = false;
constructor(private userService: UserService, private http: HttpClient) {
}
ngOnInit() {
this.getRecords();
}
getRecords(){
this.getResultedPage(1);
}
getResultedPage(page){
return this.userService.getrecords()
.subscribe(response => {
this.list = response.data;
});
}
}
Service
import { Injectable } from '#angular/core';
import { Observable, of, throwError } from 'rxjs';
import { HttpClient, HttpParams , HttpErrorResponse, HttpHeaders } from '#angular/common/http';
import { map, catchError, tap, switchMap } from 'rxjs/operators';
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
};
import { UtilsService } from '../../services/utils.service';
import { AppConfig } from '../../../config/app'
#Injectable({
providedIn: 'root'
})
export class UserService{
public appConfig: AppConfig;
public API_URL;
constructor(private http: HttpClient, private util: UtilsService) {
this.appConfig = new AppConfig();
this.API_URL = this.appConfig.config.api_url;
}
private extractData(res: Response) {
let body = res;
return body || { };
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError('Something bad happened; please try again later.');
};
getrecords(): Observable<any> {
return this.http.get('/api/users', httpOptions).pipe(
map(this.extractData),
catchError(this.handleError));
}
}

angular resolver does not have access to angular service properties

i have an anagular service called authservice ,which looks like this:
import { Injectable } from '#angular/core';
import { Http, Headers, RequestOptions, Response } from '#angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { JwtHelperService} from '#auth0/angular-jwt';
#Injectable()
export class AuthService {
public DecdedToken: any;
userToken: any;
public userid: any;
helper: any = new JwtHelperService();
baseUrl = 'http://localhost:5000/api/auth/';
// userToken: any;
constructor(private http: Http , private jwthelpservicee: JwtHelperService) {}
login(model: any) {
return this.http.post(this.baseUrl + 'login', model, this.requestOptions()).map((response: Response) => {
const user = response.json();
if (user && user.stringToken) {
this.userToken = user.stringToken;
localStorage.setItem('token', user.stringToken);
this.DecdedToken = this.helper.decodeToken(user.stringToken);
this.userid = this.DecdedToken.nameid;
// console.log(this.userid);
// onsole.log('so far so good');
}
}).catch(this.HandleError);
}
register(model: any) {
return this.http.post(this.baseUrl + 'register', model, this.requestOptions()).catch(this.HandleError);
}
private requestOptions() {
const headers = new Headers({ 'Content-type': 'application/json' });
return new RequestOptions({ headers: headers });
}
IsLoggedIn() {
return !this.jwthelpservicee.isTokenExpired();
}
private HandleError(error: any) {
const applicationerror = error.headers.get('Application-Error');
if (applicationerror) {
return Observable.throw(applicationerror);
}
const serverError = error.json();
let modelStateErrors = '';
if (serverError) {
for (const key in serverError) {
if (serverError[key]) {
modelStateErrors += serverError[key] + '\n';
}
}
}
return Observable.throw(modelStateErrors || 'server error');
}
}
in login method DecodedToken gets its value.
i have a resolver too, in which i am trying to get a value of a property from authsercvice
import { Resolve, Router, ActivatedRouteSnapshot } from '../../../node_modules/#angular/router';
import { User } from '../_Models/user';
import { Injectable } from '../../../node_modules/#angular/core';
import { UserService } from '../_services/User.service';
import { AlertifyService } from '../_services/alertify.service';
import { Observable } from '../../../node_modules/rxjs';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/catch';
import { AuthService } from '../_services/auth.service';
#Injectable()
export class MemberEditResolver implements Resolve<User> {
constructor(private userservice: UserService ,
private router: Router ,
private alertify: AlertifyService,
private authservice: AuthService) {
}
resolve(route: ActivatedRouteSnapshot): Observable<User> {
console.log(this.authservice.userid);
return this.userservice.getuser(this.authservice.DecdedToken.nameid).catch(error => {
this.alertify.error('error');
this.router.navigate(['/members']);
return Observable.of(null);
});
}
}
as you can see i have defined DecdedToken as a public property, inside the authservice this property has value, but when i want to access it from resolver ,i get null or undefined...

res.json() does not exist [duplicate]

This question already has answers here:
res.json() is a not a function in HttpClient Angular 2
(2 answers)
Closed 4 years ago.
I am trying to create a simple post in a service class using Angular/Typescript
My IDE does not give me any error, but when I call the function, I am getting undefined. I am not sure where the problem is based. I did some research, and it seems like the problem might be with the HttpClient I am importing, but I can not find anything relevant.
Front-end Function:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders} from '#angular/common/http';
import { Response } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class ServiceClassAuth {
auth: any;
user: any;
constructor(private http: HttpClient) {}
signinUser(user) {}
login(user) {
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
const loginUrl = 'http://localhost:3000/login';
return this.http.post(loginUrl, user, {
headers: headers
}).map((res: Response) => res.json());
}
}
A component which calls the Service:
import { Component, OnInit } from '#angular/core';
import {
MatDialog,
MatDialogRef,
MAT_DIALOG_DATA
} from '#angular/material';
import { Inject } from '#angular/core';
import { ServiceClassAuth } from '../service/service-class-auth';
#Component({
selector: 'app-signin',
templateUrl: './signin.component.html',
styleUrls: ['./signin.component.css'],
providers: [ServiceClassAuth]
})
export class SigninComponent implements OnInit {
username: String;
password: String;
ngOnInit() {}
constructor(
public dialogRef: MatDialogRef < SigninComponent > ,
#Inject(MAT_DIALOG_DATA) public data: any,
private authService: ServiceClassAuth) {}
onNoClick(): void {
this.dialogRef.close();
}
loginSubmit(postValues): void {
const user = {
'usr': postValues.value.usrname,
'psw': postValues.value.psw
}
const res = this.authService.login(user).subscribe(res => {
if (res.success) {
} else {
//DO ALERT
}
});
}
}
With HttpClient (Angular 4.3+), you do not have to use res.json() , the response object is JSON by default, Just use response directly.
return this.http.post(loginUrl, user, {
headers: headers
}).map((res: Response) => res);

Angular 5 component expecting an argument

Im trying a simple profile app, and all the sudden Im getting error TS2554
ERROR in /app/components/profile/profile.component.ts(25,3): error TS2554: Expected 1 arguments, but got 0.
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../../services/auth.service';
import { FlashMessagesService } from 'angular2-flash-messages';
import { Router } from '#angular/router';
#Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
user: Object;
constructor(
private auth: AuthService,
private flashMsg: FlashMessagesService,
private router: Router
) {
}
ngOnInit() {
this.auth.getProfile().subscribe( profile => {
this.user = profile.user;
},
err => {
return false;
});
}
}
auth.service.ts
import { Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http';
import 'rxjs/add/operator/map';
import { tokenNotExpired } from 'angular2-jwt';
#Injectable()
export class AuthService {
authToken: any;
user: any;
constructor(
private http: Http
) {
}
getProfile(user) {
let headers = new Headers();
this.loadToken();
headers.append('Authorization', this.authToken);
headers.append('Content-Type','application/json');
return this.http.get('http://localhost:3000/users/profile', {headers:headers})
.map(res => res.json());
}
loadToken() {
const token = localStorage.getItem('id_token');
this.authToken = token;
}
}
Your getProfile is expecting an argument named user but you are not passing it from the component
You need to pass an argument as follows,
this.auth.getProfile(user).subscribe( profile => {
this.user = profile.user;
},
err => {
return false;
});
or if you don't need an argument , remove it from your service method.

render html after completion process of component in angular2

I am calling a api in my app component after getting the response I can decide which div is to show and which div is to hide.
But it render the html before completion of component process.
Below are the code example.
user.service.ts
import { Injectable } from '#angular/core';
import {Http,Headers, RequestOptions, Response, URLSearchParams} from '#angular/http';
#Injectable()
export class UserService {
private static isUserLoggedIn: boolean = false;
private userData: any;
constructor(private http: Http) { }
public isLoggedIn() {
return UserService.isUserLoggedIn;
}
public getUserData() {
return this.userData;
}
setUserData() {
var url = 'http://api.example.in/user/logincheck';
this.http
.get(url)
.map(response => response.json())
.subscribe(
(data) => {
this.userData = data;
if (typeof this.userData.id != 'undefined' && this.userData.id > 0) {
UserService.isUserLoggedIn = true;
}
},
(err) => { throw err; }
);
}
}
app.component.ts
import { Component, OnInit } from '#angular/core';
import { UserService } from './services/user/user.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [UserService],
})
export class AppComponent {
constructor(private userService: UserService) {
this.userLoggedInCheck();
}
ngOnInit() {
}
userLoggedInCheck() {
this.userService.setUserData();
}
}
I want here to load html after complete of userLoggedInCheck function called.
return a true value from userLoggedInCheck if the necessary conditions are met and assign it to a variable in the app.component.ts file. In the html file place the content within an *ngIf based on the return variable from the function.
for eg.
userLoggedInCheck() {
this.showHtml = this.userService.setUserData();
}
and in html
<div *ngIf="showHtml">
....... // code
</div>

Categories

Resources