简体   繁体   English

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

[英]How to share variables between components (Angular)?

I have two components and I am trying to export data (two variables), to the details component from login component.我有两个组件,我正在尝试将数据(两个变量)从登录组件导出到详细信息组件。 I have routing enabled.我启用了路由。 I does not seem to work.我似乎没有工作。 Where do I bind the variable?我在哪里绑定变量? I want to show a details component on a new link where I can use these two variables.我想在一个新链接上显示一个详细信息组件,我可以在其中使用这两个变量。

login.component.ts登录.component.ts

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

details.component.ts details.component.ts

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

}

details.component.html详细信息.component.html

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

</app-details>

login.component.html登录.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>

One of the ways you can achieve this is to pass imageUrl and email as queryParams with the routerLink that navigates to the details component.实现此目的的方法之一是将imageUrlemail作为queryParams传递,并使用导航到details组件的routerLink You can then subscribe to the ActivatedRoute's queryParams observable on the DetailsComponent to get the variables.然后,您可以订阅ActivatedRoute's queryParams观察到的DetailsComponent得到的变量。 On the LoginComponent template have this:LoginComponent模板上有这个:

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

Then on the DetailsComponent you can have this:然后在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM