如何在组件之间共享变量(Angular)



我有两个组件,我正在尝试将数据(两个变量(从登录组件导出到细节组件。我已启用路由。我似乎不工作。在哪里绑定变量?我想在一个新的链接上显示一个细节组件,在那里我可以使用这两个变量。

登录组件.ts

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

details.component.ts

export class DetailsComponent implements OnInit {

@Input() imgURL;
@Input() email;
}

details.component.html

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

login.component.html

<div class="container mt-5">
<h2>Google Login</h2>
<div class="row mt-5">
<div class="col-md-4 mt-2 m-auto ">
<button class="login-Btn" #loginRef>
Login with Google<img class="social-btn-icon" alt="Login with Google" src="https://hrcdn.net/fcore/assets/google-colored-20b8216731.svg">
</button>
<a routerLink="/details" routerLinkActive="active">Details</a>
</div>   
</div>
</div>

实现这一点的方法之一是将imageUrlemail作为queryParams传递,routerLink导航到details组件。然后,您可以订阅DetailsComponent上可观察到的ActivatedRoute'squeryParams以获取变量。在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'];
});
}
}

最新更新