Angular 2 具有特定 url 的路由
Angular 2 Routing with a specific url
我目前正在开发一个 angular 应用程序,该应用程序在特定 url 上打开:
localhost:3000/?param1=abc,def¶m2=abcdefghi
现在我想实现 angular 路由。
所以我有 2 条路线:1. mainComponent 2.dataComponent
在我的 index.html 中,设置为:
<base href="/">
将应用配置为使用路由后,我的应用打开时只有 localhost:3000 ,即使在将 param1、param2 添加到 url 之后,它也会被重定向到 localhost:3000
我该如何解决这个问题?因为参数仅在打开时传递 link 并且它是动态的
app.module.ts:
const appRoutes: Routes = [
{ path: 'mainComponent', component: MainComponent },
{ path: 'dataComponent', component: DataComponent },
{path : '' , component:MainComponent}
];
app.component.html:
<nav>
<a routerLink="/mainComponent" routerLinkActive="active">Main</a>
<a routerLink="/dataComponent" routerLinkActive="active">Data</a>
</nav>
<router-outlet></router-outlet>
您需要按照以下方式更改路线
const appRoutes: Routes = [
{path : '' ,redirectTo: 'mainComponent', pathMatch: 'full'},
{ path: 'mainComponent', component: MainComponent },
{ path: 'dataComponent', component: DataComponent },
];
以及提供链接的更好方式
<nav>
<a [routerLink]="['/mainComponent']" routerLinkActive="active">Main</a>
<a [routerLink]="['/dataComponent']" [queryParams]="{ param: "paramValue" } routerLinkActive="active">Data</a>
</nav>
要接收参数,您需要在组件构造函数中执行以下操作
constructor(private activatedRoute: ActivatedRoute){
this.type = activatedRoute.snapshot.params['type'];
}
我目前正在开发一个 angular 应用程序,该应用程序在特定 url 上打开:
localhost:3000/?param1=abc,def¶m2=abcdefghi
现在我想实现 angular 路由。
所以我有 2 条路线:1. mainComponent 2.dataComponent
在我的 index.html 中,设置为:
<base href="/">
将应用配置为使用路由后,我的应用打开时只有 localhost:3000 ,即使在将 param1、param2 添加到 url 之后,它也会被重定向到 localhost:3000
我该如何解决这个问题?因为参数仅在打开时传递 link 并且它是动态的
app.module.ts:
const appRoutes: Routes = [
{ path: 'mainComponent', component: MainComponent },
{ path: 'dataComponent', component: DataComponent },
{path : '' , component:MainComponent}
];
app.component.html:
<nav>
<a routerLink="/mainComponent" routerLinkActive="active">Main</a>
<a routerLink="/dataComponent" routerLinkActive="active">Data</a>
</nav>
<router-outlet></router-outlet>
您需要按照以下方式更改路线
const appRoutes: Routes = [
{path : '' ,redirectTo: 'mainComponent', pathMatch: 'full'},
{ path: 'mainComponent', component: MainComponent },
{ path: 'dataComponent', component: DataComponent },
];
以及提供链接的更好方式
<nav>
<a [routerLink]="['/mainComponent']" routerLinkActive="active">Main</a>
<a [routerLink]="['/dataComponent']" [queryParams]="{ param: "paramValue" } routerLinkActive="active">Data</a>
</nav>
要接收参数,您需要在组件构造函数中执行以下操作
constructor(private activatedRoute: ActivatedRoute){
this.type = activatedRoute.snapshot.params['type'];
}