如何在组件之间共享变量(角度)?

时间:2020-09-28 09:25:38

标签: angular typescript templates

我有两个组件,我正在尝试将数据(两个变量)从登录组件导出到详细信息组件。我启用了路由。我似乎没有工作。我在哪里绑定变量?我想在新链接上显示一个details组件,在其中可以使用这两个变量。

login.component.ts

Console.Write

details.component.ts

export class LoginComponent implements OnInit {
  imgURL = "link";
  email = "email";
}

details.component.html

export class DetailsComponent implements OnInit {
  
  @Input() imgURL;
  @Input() email;

}

login.component.html

<app-details [imgURL]="imgURL">
    {{imgURL}}

</app-details>

1 个答案:

答案 0 :(得分:0)

实现此目标的方法之一是使用imageUrl作为email传递queryParamsrouterLink并导航到details组件。然后,您可以订阅ActivatedRoute's上可观察到的queryParams DetailsComponent以获取变量。 在LoginComponent模板上有以下内容:

<a [routerLink]="['/details']" [queryParams]="{ email: {{email}}, imgUrl: {{imgUrl}} }" routerLinkActive="active">Details</a>

然后在DetailsComponent上输入以下内容:

export class DetailsComponent implements OnInit {

  imgUrl: string;
  email: string;

  constructor(
    private route: ActivatedRoute,
  ) {}

  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      this.email = params['email'];
      this.imgUrl = params['imgUrl'];
    });
  }
}
相关问题