16

I have an angular component with a @Input parameter as follows.

@Component({
  selector: 'app-transmission-history'
})
export class TransmissionHistoryComponent implements OnInit {

  @Input() theRecord: Record = null;

  constructor(private _transmissionHistoryService: TransmissionHistoryService) { }
}

In another component I have this in the markup:

<app-transmission-history [theRecord]="selectedRecord"></app-transmission-history>

Perfect. Everything works as expected.

I need to move the app-transmission-history component to a stand alone page. Now I need to access it with routerLink as follows:

<a routerLink='/transmissionHistory'>{{selectedRecord.Name}}</a>

I can't figure out how to set the @Input parameter in the routerlink in the markup. The value I need to set it to is selectedRecord, which I have access to.

I could make changes to the app-transmission-history component to receive the parameter another way. However, it does not seem flexible if I have to change the implementation based on how we get to it.

4

3 回答 3

18

转换为 json 字符串后使用查询参数传递对象。

<a [routerLink]="['/transmissionHistory']"
   [queryParams]="{record:selectedRecord | json }">
    {{selectedRecord.Name}}
</a>

在您的组件中,您可以执行以下操作来读取参数:

@Component({
  selector: 'app-transmission-history'
})
export class TransmissionHistoryComponent implements OnInit {
  theRecord: Record = null;

  constructor(
      private _transmissionHistoryService: TransmissionHistoryService,
      private _route: ActivatedRoute

   ) { }

   ngOnInit() {
      this._route.params.subscribe(params => {
          this.theRecord = JSON.parse(params.record) as Record;
      });
   }
}

路由器配置将如下所示:

{ path: 'transmissionHistory', component: TransmissionHistoryComponent }
于 2018-07-08T23:07:18.600 回答
6

请看一下路由器参数。你可以像这样传递你的参数:

<a [routerLink]="['/transmissionHistory', selectedRecord]">{{selectedRecord.Name}}</a>

比在您的组件中,您可以像这样检索它:

@Component({
  selector: 'app-transmission-history'
})
export class TransmissionHistoryComponent implements OnInit {
  theRecord: Record = null;

  constructor(
      private _transmissionHistoryService: TransmissionHistoryService,
      private _route: ActivatedRoute

   ) { }

   ngOnInit() {
      this._route.params.subscribe(params => {
          this.theRecord = params['record'];
      });
   }
}

请记住在您的路由器配置中设置此参数:

{ path: 'transmissionHistory/:record', component: TransmissionHistoryComponent }
于 2017-12-15T16:25:12.167 回答
0

如何在Angular中的路由组件之间传递数据

于 2021-08-02T18:15:11.310 回答