【问题标题】:How to pass a Date object as a parameter in routerLink in Angular如何在Angular的routerLink中将日期对象作为参数传递
【发布时间】:2020-10-26 18:41:24
【问题描述】:

这是我的代码块。在这里,我试图将 checkinFrom 日期对象作为 routerLink 中的参数获取到另一个组件。

<app-chart-chip [routerLink]="['/statistics/subsegment',currentPS,checkinFrom]"
                                   [currentPS]="currentPS" [fromDate]="checkinFrom">
            </app-chart-chip>

这是我的父组件代码。

 currentPS: string;
    checkinFrom = new Date(2019, 8, 1);
    ngOnInit() {
     this.currentPS = 'PS';
    
    }

这是子组件代码

export class ChartChipComponent implements OnInit, OnChanges{
     @Input() fromDate = new Date();
     @Input() currentPS: string;
}

这是 app.routing.module.ts 文件

{
    path: 'statistics/subsegment/:currentPS/:fromDate',
    component: StatisticsComponent,
    loadChildren: 'src/app/statistics/statistics.module#StatisticsModule',
    data: {
      title: 'Subsegmentation'
    }
  }

对于这个组件,我试图在 URL 中的 routerLink 中获取日期作为参数

export class StatisticsComponent implements OnInit {

 ngOnInit() {
   this.getParticularId();
}
getParticularId() {
    this.route.params.subscribe( params => {
    console.log(params);
}
}

但它正在重定向到仪表板。

{
    path: '**',
    redirectTo: 'dashboard',
    pathMatch: 'full'
  }

【问题讨论】:

    标签: angular typescript url routes


    【解决方案1】:

    你传递日期的方式很好,但我认为 routerLink 是错误的。

    试试这个:

      constructor(private route: ActivatedRoute) { }
    
      this.route.paramMap.subscribe(params => {
        console.log(params)
      })
    

    HTML:

      [routerLink]="['/', 'statistics', 'subsegment', currentPS,checkinFrom]"
    

    【讨论】:

    • 但我可以通过这种方式获得currentPS 值。只有我无法获得的日期
    • 什么是参数打印?
    • 只有这些参数 currentPS,checkinFrom
    • 我知道,但它实际打印的是什么,我会使用 paramMap 而不是 param
    • 当第一次重新加载父组件html时,它会在子组件中打印ngOnChanges(changes: SimpleChanges) { console.log(this.currentPS); console.log(this.fromDate); }
    【解决方案2】:

    在应用图表芯片中添加如下代码

    [queryParams]="{date:checkinFrom }"

    <app-chart-chip [routerLink]="['/statistics/subsegment',currentPS,checkinFrom]"
         [queryParams]="{date:checkinFrom }"                              [currentPS]="currentPS" [fromDate]="checkinFrom">
                </app-chart-chip>
    

    你可以这样获取日期

    new URLSearchParams(new URL('http://localhost:4400/dashboard?date=Sun%20Sep%2001%202019%2000:00:00%20GMT%2B0530%20(India%20Standard%20Time').search).get('date');
    

    输出 "Sun Sep 01 2019 00:00:00 GMT+0530 (India Standard Time"

    【讨论】:

    • 然后它将定向到这样的网址 [link] localhost:4400/…
    • 实际上是指向仪表板
    【解决方案3】:

    试试这个:

    [routerLink]="['/consultation/calendar/']"
    [queryParams]="{ date: lastAppointment?.startDate }"
    

    然后:

    this.route.snapshot.queryParams['date']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-29
      • 2015-04-04
      • 2018-12-11
      • 2011-08-29
      • 1970-01-01
      • 2019-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多