Angular 路由:将动态 url 数据传递给组件

Angular Routing: Passing dynamic url data to components

我有以下路线:

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 中使用这些数据?

在你的构造函数中

public constructor(private route:ActivatedRoute, private router:Router) {
      console.log(route.snapshot.data['country']);
  }

或者您可以根据路由器插座 (check here) 中的文档使用以下内容

export class AppComponent {
  getCountryData(outlet: RouterOutlet) {
    return outlet && outlet.activatedRouteData && outlet.activatedRouteData['country'];
  }
}

您不需要数据对象中的国家 属性。 url 中的国家信息应该足够了。

从路由中检索国家参数:

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

这样试试:

WORKING DEMO // 点击主页

import { ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) {
  alert(route.snapshot["data"].country)
}

您不需要通过这种方式country: ':country'。 通过使用这种方式,您可以读取路径变量

import {  ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) {
  alert(route.snapshot["data"].country)
}