【问题标题】:Angular Routing: Passing dynamic url data to componentsAngular Routing:将动态 url 数据传递给组件
【发布时间】:2019-11-13 11:35:49
【问题描述】:

我有以下路线:

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' 是向SignUpComponent 传递动态 url 数据的正确方法吗?如果是,我如何在我的SignUpComponent Component 中使用这些数据?

【问题讨论】:

    标签: angular typescript routing


    【解决方案1】:

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

    从路由中检索国家参数:

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

    【讨论】:

      【解决方案2】:

      试试这样:

      WORKING DEMO // 点击主页

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

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

      【讨论】:

        【解决方案3】:

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

        import {  ActivatedRoute } from '@angular/router';
        
        constructor(private route: ActivatedRoute) {
          alert(route.snapshot["data"].country)
        }
        

        【讨论】:

          【解决方案4】:

          在你的构造函数中

          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'];
            }
          }
          

          【讨论】:

            猜你喜欢
            • 2017-06-15
            • 2017-01-07
            • 1970-01-01
            • 2019-01-03
            • 2018-05-28
            • 2021-04-12
            • 2020-05-26
            • 1970-01-01
            • 2019-01-02
            相关资源
            最近更新 更多