angular 2 路由 url 问题
angular 2 routing url issue
这是我的 app.module.ts 文件。
imports: [
UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'subscriber', component: SubscriberComponent },
{ path: '**', redirectTo: 'home' }
]),
//HttpModule
FormsModule
]
在我的订阅者组件中,我从 ngOnInit
中的 url 获取了一个参数
ngOnInit() {
let id = '';
this.activatedRoute.params.subscribe((params: Params) => {
id = params['id'];
if (id != '') {
this.viewData(id);
}
console.log(id);
});
}
效果很好,但每次我使用 url 获取参数(xxx),例如http://localhost:60009/xxx
我收到一个错误,因为路由重定向到这个 url,显然我没有任何链接。知道如何从路由中跳过重定向吗?
如果您使用路由参数,则需要在路由配置中指定它们。您正在尝试读取参数 id
,但配置中的路由未指定 id
。尝试将其添加到您的配置中:
{ path: ':id', redirectTo: 'home', pathMatch: 'full' },
编辑
Angular既有路由参数也有查询参数。路由参数在路由配置中指定,如下所示:
{ path: ':id', redirectTo: 'home', pathMatch: 'full' },
您将访问组件中的那些:
this.route.params.subscribe(data => data['id']);
那么你也有查询参数。这些未在路由配置中指定。它们在 url 中看起来像这样: ?id=something
您可以在您的组件中访问它们:
this.route.queryParams.subscribe(queryParams => queryParams['id']);
主要区别在于您在激活的路由上使用 params
还是 queryParams
以及是否在路由配置中指定了参数。
这是我的 app.module.ts 文件。
imports: [
UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'subscriber', component: SubscriberComponent },
{ path: '**', redirectTo: 'home' }
]),
//HttpModule
FormsModule
]
在我的订阅者组件中,我从 ngOnInit
中的 url 获取了一个参数ngOnInit() {
let id = '';
this.activatedRoute.params.subscribe((params: Params) => {
id = params['id'];
if (id != '') {
this.viewData(id);
}
console.log(id);
});
}
效果很好,但每次我使用 url 获取参数(xxx),例如http://localhost:60009/xxx 我收到一个错误,因为路由重定向到这个 url,显然我没有任何链接。知道如何从路由中跳过重定向吗?
如果您使用路由参数,则需要在路由配置中指定它们。您正在尝试读取参数 id
,但配置中的路由未指定 id
。尝试将其添加到您的配置中:
{ path: ':id', redirectTo: 'home', pathMatch: 'full' },
编辑
Angular既有路由参数也有查询参数。路由参数在路由配置中指定,如下所示:
{ path: ':id', redirectTo: 'home', pathMatch: 'full' },
您将访问组件中的那些:
this.route.params.subscribe(data => data['id']);
那么你也有查询参数。这些未在路由配置中指定。它们在 url 中看起来像这样: ?id=something
您可以在您的组件中访问它们:
this.route.queryParams.subscribe(queryParams => queryParams['id']);
主要区别在于您在激活的路由上使用 params
还是 queryParams
以及是否在路由配置中指定了参数。