I need to create a web portal that will be embedded inside an iFrame.
Here is the code I use to bootstrap the portal
Routes configuration
const routes: Routes = [
{
path: '',
redirectTo: '/dashboard',
pathMatch: 'full'
},
{
path: 'dashboard',
component: DashboardComponent
},
{
path: 'userinformation',
component: UserInformationComponent
}
];
Simplified index.html
<!doctype html>
<html lang="en">
<head>
<base href="/">
</head>
<body>
<frontend-root></frontend-root>
</body>
</html>
The AppComponent
import { Component } from '@angular/core';
@Component({
selector: 'frontend-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'frontend';
}
The 'app' component html
<div style="text-align:center">
<h1>Portal Main Menu</h1>
</div>
<div class="container-fluid">
<div class="row">
<div class="col" style="background-color: greenyellow">
<left-menu></left-menu>
</div>
<div class="col-10" style="background-color: yellow">
<router-outlet></router-outlet>
</div>
</div>
</div>
So the app.component.html file contains the 'router-outlet' where my 'dashboard' and/or my 'userinformations' will be rendered.
Everything works fine, except that the launching application that owns the iframe will send parameters to my webpage thanks to a URL like this one:
http://myportal.com/?language=fr&userId=12345
And I would like to retrieve these parameters from my AppComponent which is the bootstrapped component.
I tried to use the following solution to retrieve query parameters https://stackoverflow.com/a/39915434/1636492
But as I have a 'default' webpage and a router-outlet not located at the root of my html page, this is not working.
Here are the problems I encountered:
After a while, I found the solution for my app thanks to this link https://github.com/angular/angular/issues/12157
In the AppComponent, I use this function:
function getParameterByName(name: any) {
const url = window.location.href;
name = name.replace(/[[]]/g, '\$&');
const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'), results = regex.exec(url);
if (!results) {
return null;
}
if (!results[2]) {
return '';
}
return decodeURIComponent(results[2].replace('/+/g', ' '));
}
And in the ngOnInit of the AppComponent, you can retrieve all needed parameters:
ngOnInit(): void {
let value1 = getParameterByName('value1');
let value2 = getParameterByName('value2') || ''; // not mandatory
// do something with value1 & value 2
}