[英]How to share variables between components (Angular)?
我有兩個組件,我正在嘗試將數據(兩個變量)從登錄組件導出到詳細信息組件。 我啟用了路由。 我似乎沒有工作。 我在哪里綁定變量? 我想在一個新鏈接上顯示一個詳細信息組件,我可以在其中使用這兩個變量。
登錄.component.ts
export class LoginComponent implements OnInit {
imgURL = "link";
email = "email";
}
details.component.ts
export class DetailsComponent implements OnInit {
@Input() imgURL;
@Input() email;
}
詳細信息.component.html
<app-details [imgURL]="imgURL">
{{imgURL}}
</app-details>
登錄.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>
實現此目的的方法之一是將imageUrl
和email
作為queryParams
傳遞,並使用導航到details
組件的routerLink
。 然后,您可以訂閱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'];
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.