Angular 4应用程序,默认页面和url中的参数

时间:2017-09-19 17:44:11

标签: html angular typescript iframe angular-router

我需要创建一个嵌入在iFrame中的Web门户。

以下是我用来引导门户网站的代码

路线配置

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

&#39; app&#39;组件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文件包含&#39; router-outlet&#39;我的仪表板&#39;和/或我的用户信息&#39;将被渲染。

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

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

我想从我的AppComponent中检索这些参数,这是一个自举组件。

我尝试使用以下解决方案来检索查询参数     https://stackoverflow.com/a/39915434/1636492

但是我有一个&#39;默认&#39;网页和路由器插座不在我的html页面的根目录,这不起作用。

以下是我遇到的问题:

  • 我不能在路线中同时使用组件和redirectTo 定义(我使用了route.redirect到我的OnInit中 AppComponent)
  • 在根示例中,作者放置了标记。但是当我的应用程序中包含路由器插座时,无法找到它。

1 个答案:

答案 0 :(得分:1)

过了一会儿,我找到了我的应用程序的解决方案,感谢这个链接 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  
}