我已经在 Angular JS 中为同一项目中的其他组件成功实现了路由参数,对于新组件,我也遵循相同的方式,但它不起作用,我无法理解代码中的问题。
下面是我的路由文件的代码
import { Routes, RouterModule } from '@angular/router';
import { CustomerBillComponent } from '../components/customer_bill.component';
const routes: Routes = [
{ path: 'add-bill', component: CustomerBillComponent },
{ path: 'add-bill/:customer_reference', component: CustomerBillComponent },
];
export const routing = RouterModule.forRoot(routes);
(我也尝试使用不同的路线,但没有成功)
下面是我的 CustomerBillComponent.ts 文件中的代码
ngOnInit() {
//When I visit /#/add-bill/CR452152
let route_location = location['hash'].split('/')[1].toLowerCase();
console.log(route_location); //prints add-bill in Console
var customer_reference = this.route.snapshot.params['customer_reference'];
console.log(customer_reference); //prints undefined
}
我是不是错过了什么
提前致谢!!!
最佳答案
我面临着几乎同样的问题。但原因不同。
在我的场景中,借贷页面(路由上指定的组件)不同,我试图访问父路由组件上的路由参数。
下面是演示我的场景的代码:
home.module.routing.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
//other import statements...
const routes: Routes = [
{
path: 'home', component: HomeComponent,
children: [
{ path: 'buy/:mainType/:subType', component: BuyComponent, data: {} },
{ path: 'buy/:mainType', component: BuyComponent, data: { } },
{ path: '', redirectTo: 'buy', pathMatch: 'full' },
]
},
{ path: 'checkout', component: CheckoutCartComponent },
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class HomeRoutingModule { }
因此,我必须访问 HomeComponent(Parent)中的 RouteParam 值,而 Lending 页面是 BuyComponent(HomeComponent 的子路由)。
所以,我没有使用下面的代码获取路由参数的值:
//HomeComponent.ts 内部
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.routeText = params['category'];
this.title = this.formatTitle(this.routeText);
});
}
由于借贷页面是BuyComponent,所以上面的代码不起作用。 Angular 只允许在登陆组件上以上述方式访问路由参数。
我尝试了很多,终于找到了访问父路由组件中的路由参数的解决方案。
下面是访问相同内容的代码:
//HomeComponent.ts 内部
const routeChildren = this.activatedRoute.snapshot.children;
if (routeChildren.length) {
//Your code here to assign route params to the Component's Data Member.
}
因此,访问 this.activatedRoute.snapshot.children
而不是 this.route.params
对我来说是成功的。
如果有人像我一样来到这里寻找问题,希望这会有所帮助。
最诚挚的问候。
关于javascript - 无法读取 Angular 2 中的路由参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43362389/