首页 > 解决方案 > Angular Routing:将动态 url 数据传递给组件

问题描述

我有以下路线:

const routes: Routes = [
    {
        path: ':product/new',
        children: [{
            path: 'std/:country',
            component: SignUpComponent,
            data: {
                animation: 'animate',
                segment: 'std',
                country: ':country'
            }
        }, {
            path: 'exp/:country',
            component: PaymentComponent,
            data: {
                animation: 'animate',
                segment: 'exp'
            }
        }
    }
]

country: ':country'将动态 url 数据传递给的正确方法是什么SignUpComponent?如果是,我如何在我的 中使用这些数据SignUpComponent Component

标签: angulartypescriptrouting

解决方案


您不需要数据对象中的国家/地区属性。网址中的国家/地区信息应该足够了。

从路由中检索国家参数:

class  SignUpComponent implements OnInit {
  constructor(private activatedRoute: ActivatedRoute) {}
  ngOnInit() {
    this.activatedRoute.params.subscribe((params) => {
        // params.country should be defined here    
    });
 }
}

推荐阅读