RouterLink抛出错误'无法读取属性'频率'未定义的'

时间:2018-02-15 08:56:07

标签: angular angular4-router

在我的angular 4应用程序中,我在视图中有以下HTML

<p>
    You are on dasrboard(firstlevel);
    <a [routerLink]="['/seconddashboard',{frequency:frequency, datefrom:datefromparam, dateto:datetoparam}]"><button class="btn btn-success pull-right" > Second Level (sc) </button></a> 
</p>

并在组件

中使用以下代码
export class DashBoardComponent implements OnInit {

  frequency = '';
  datefromparam='';
  datetoparam='';

  constructor(private dataService:ChartdataService,private _alertService: AlertService) { 
  // this.InitChildComponents();
    this.frequency = 'daily';
    this.datefromparam='';
    this.datetoparam='';
}

但是在页面加载时,它会给出错误Cannot read property 'frequency' of undefined。有人可以在我做错的地方帮助我吗?

Error in routes definition

2 个答案:

答案 0 :(得分:1)

你应该在构造函数

中使用这个关键词
 export class DashBoardComponent implements OnInit {

 frequency = '';
  datefromparam='';
 datetoparam='';

 constructor(private dataService:ChartdataService,private _alertService: 
 AlertService) { 
 // this.InitChildComponents();
   this.frequency = 'daily';
   this.datefromparam='';
   this.datetoparam='';

}

答案 1 :(得分:0)

如果您想使用角度路由器传递和读取数据,则必须stringify传递数据:

<p>
    You are on dasrboard(firstlevel);
    <a [routerLink]="['/seconddashboard', {
      queryParams: {
        'data': JSON.stringify({
          frequency: frequency,
          datefrom: datefromparam,
          dateto: datetoparam
        })
      }
    }]"><button class="btn btn-success pull-right" > Second Level (sc) </button></a> 
</p>

路线应如下所示:

const routes: Routes = [
  {
    path: 'seconddashboard',
    component: DashBoardComponent
  },
  // other routes
];

然后,在收件人组件中,您可以使用this.route.snapshot.data

读取传递的数据
import { Router, ActivatedRoute, Params, Data } from '@angular/router';
// other imports

// @NgModule and other stuff

export class DashBoardComponent {
  frequency = '';
  datefromparam = '';
  datetoparam = '';

  constructor(
    private dataService: ChartdataService,
    private _alertService: AlertService,
    private route: ActivatedRoute,
    private router: Router
  ) { 
    // this.InitChildComponents();
    this.route
      .queryParams
      .subscribe(t => {
        // may be you also need to do `JSON.parse(t['data'])`
        console.log(t['data']);
        // may be I missed something in path below, but you can easily correct it based on 'console.log' above
        this.frequency = t.data.frequency;
        this.datefromparam = t.data.datefromparam;
        this.datetoparam = t.data.datetoparam;
      });
  }
}

不要忘记在构造函数中使用this,例如this.frequency = "SOMETHING"