将参数发送到另一个组件

时间:2018-08-24 14:02:26

标签: angular typescript parameters routing

导航后,我试图将idAgreement的值从一个组件发送到另一个组件,这是我的代码:

component.ts

  onSelectAgreement(selectedAgreementList: Agreement) {debugger;
    this.selectedAgreementList = selectedAgreementList;
    if (this.selectedAgreementList) {
      console.log("row selected: " + this.selectedAgreementList.idAgreement);
      this.saveState(this.lastRequestUri, this.router.url);
      this.router.navigate(['/newagreement']);
      this.accordiService.loadAgreement(this.selectedAgreementList.idAgreement);
    }
  }

基本上(this.selectedAgreementList.idAgreement)应该发送到组件/newagreement

我该怎么做?

编辑:

第一部分:

 onSelectAgreement(selectedAgreementList: Agreement) {debugger;
    this.selectedAgreementList = selectedAgreementList;
    if (this.selectedAgreementList) {
      console.log("row selected: " + this.selectedAgreementList.idAgreement);
      this.saveState(this.lastRequestUri, this.router.url);
      this.router.navigate(['/newagreement',[this.selectedAgreementList.idAgreement]]);
    }   }
  

第二部分:

  private sub: any;
  value: string;

  ngOnInit() {

    this.sub = this.route.params.subscribe(params => {
      this.value= params['idAgreement'];

   });
    this.loadAgreement(this.idAgreement);}
}

2 个答案:

答案 0 :(得分:1)

现在您正在使用路线参数,您可以从this.route.params(现在是地图对象)中获取值。

要获取idAgreement的值,您需要使用this.route.params.get('idAgreement')

如果您使用的是ActivatedRoute,则可以这样获得值:

constructor(private route: ActivatedRoute) {
  this.route.paramMap.subscribe((map) => {
    console.log("Value is", map.get("test"))
  })
}

Here is an example in StackBlitz

答案 1 :(得分:1)

在app-routing.module.ts中,确保您的目标组件具有此路由

 import { TargetComponent }      from   './path/your.target.component';

const routes: Routes = [
{ path: 'yourpath/:idParameterToPass', component: Targetcomponent }
];

然后在您的component.t(您的源组件)中,传递您想要的参数。

this.router.navigate(['/newagreement/123yourid456passithere']);

然后将其插入到目标组件,在构造函数中注入ActivatedRoute,并从快照获取传递的值。

 @Component({templateUrl:'./your-target-component.html'})

class TargetComponent {
  constructor(private route: ActivatedRoute) {
const id: string = this.route.snapshot.params['idParameterToPass']

  }
}