Angular 4 个具有默认页面和参数的应用程序 url

Angular 4 application with default page and parameters in url

我需要创建一个将嵌入到 iFrame 中的门户网站。

这是我用于 bootstrap 门户网站

的代码

路由配置

const routes: Routes = [
    {
      path: '',
      redirectTo: '/dashboard',
      pathMatch: 'full'
    },
    {
      path: 'dashboard',
      component: DashboardComponent
    },
    {
      path: 'userinformation',
      component: UserInformationComponent
    }
];

简体index.html

<!doctype html>
<html lang="en">
<head>
  <base href="/">
</head>
<body>
  <frontend-root></frontend-root>
</body>
</html>

AppComponent

import { Component } from '@angular/core';

@Component({
  selector: 'frontend-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'frontend';
}

'app'分量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>

因此 app.component.html 文件包含 'router-outlet',其中我的 'dashboard' and/or 我的 'userinformations' 将被渲染。

一切正常,除了拥有 iframe 的启动应用程序将参数发送到我的网页,这要归功于像这样的 URL:

http://myportal.com/?language=fr&userId=12345

我想从我的 AppComponent 中检索这些参数,它是 bootstrapped 组件。

我尝试使用以下解决方案来检索查询参数

但是因为我有一个 'default' 网页和一个路由器插座不在我的 html 页面的根目录下,所以这是行不通的。

以下是我遇到的问题:

过了一会儿,我找到了我的应用程序的解决方案,多亏了这个link https://github.com/angular/angular/issues/12157

在 AppComponent 中,我使用了这个函数:

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', ' '));
}

并且在 AppComponent 的 ngOnInit 中,您可以检索所有需要的参数:

ngOnInit(): void {
  let value1 = getParameterByName('value1');
  let value2 = getParameterByName('value2') || ''; // not mandatory
  // do something with value1 & value 2  
}