简体   繁体   English

Angular 8 在兄弟组件之间发送数据

[英]Angular 8 Send Data between sibling components

I'm using Angular 8. I have two components which are independant.我正在使用 Angular 8。我有两个独立的组件。 Form the first one I can click on a button to acces the second one.形成第一个我可以单击一个按钮来访问第二个。 The both components are not on the screen on the same time, when the second opens we don't see the first.这两个组件不在同一时间出现在屏幕上,当第二个打开时我们看不到第一个。 Under the button I use a route with routerLink to access to the second component.在按钮下,我使用带有 routerLink 的路由来访问第二个组件。 My first component is a form and there is a field with an ID.我的第一个组件是一个表单,并且有一个带有 ID 的字段。 I would like to pass this ID value from the first component to the second when I click on the button but I don't know how to do this.当我单击按钮时,我想将此 ID 值从第一个组件传递到第二个组件,但我不知道该怎么做。 How can I do this?我怎样才能做到这一点? Thanks in advance for your help.在此先感谢您的帮助。

If you look at the Angular Documentation , you'll find that there are several ways to share data between components.如果您查看Angular 文档,您会发现有几种方法可以在组件之间共享数据。 However, in this case, the most appropriate way is to use a shared service to coordinate the shared state between components.但是,在这种情况下,最合适的方式是使用共享服务来协调组件之间的共享 state。 The service will be created outside of both components and injected into them.该服务将在两个组件之外创建并注入到它们中。 The service lifetime will be the same as the application, whereas components may be created and destroyed multiple times and are not designed to hold state for any length of time.服务生命周期将与应用程序相同,而组件可能会被创建和销毁多次,并且并非旨在将 state 保持任何时间长度。

See this article for details on how to make a shared service.有关如何制作共享服务的详细信息,请参阅本文

First you need to inject a service Router inthe constructor of your first component as below.首先,您需要在第一个组件的构造函数中注入一个服务Router ,如下所示。

constructor(private router: Router) { }

Then on redirection of your routerlink you can pass the id to second component as below:然后在您的 routerlink 重定向时,您可以将 id 传递给第二个组件,如下所示:

this.router.navigate(['/second-component', Id]);

you can import Router as below:您可以按如下方式导入Router

import { Router } from '@angular/router';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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