如何将routerLink的参数传递给另一个组件的ngOnInit

时间:2018-02-04 19:14:56

标签: angular rxjs

在某些组件中我有:

<a [routerLink]="['/view-transactions', account.id]">View Transactions</a>

我的app-routing.modules.ts我有:

const routes: Routes = [
    { path: 'view-transactions/:accountid', component: TransactionComponent }

在我的transaction.component.ts中,我有:

transaction: Transaction[];

constructor(private transactionService: TransactionService,
            private route: ActivatedRoute,
            private router: Router,
            private location: Location) {
}

ngOnInit(): void {
    this.route.params
        .switchMap((params: Params) => this.transactionService.getTransactionsByAccountId(+params['id']))
        .subscribe(transaction => this.transaction = transaction);
}

导致:

  

(未知)事件处理程序出错:TypeError:无法读取属性&#39; options&#39;未定义的           在y。 (铬 - 延伸://mgijmajocgfcbeboacabfgobmjgjcoja/content.min.js:16:421)

enter image description here

1 个答案:

答案 0 :(得分:1)

您的参数不是id。根据您的路由配置,您的参数称为accountid,而不是id

请参阅{ path: 'view-transactions/:accountid', component: TransactionComponent }

因此请尝试替换:

    this.route.params
    .switchMap((params: Params) => this.transactionService.getTransactionsByAccountId(+params['id']))
    .subscribe(transaction => this.transaction = transaction);

使用:

    this.route.params
    .switchMap((params: Params) => this.transactionService.getTransactionsByAccountId(+params['accountid']))
    .subscribe(transaction => this.transaction = transaction);

它应该有用。