Angular2 在两个子组件之间传递数据
我有一个包含两个子组件的组件.我展示了一个或另一个使用带有路由器插座的路由器.
I have a component with two childcomponents. I show one or the other with using the router with the router-outlet.
我想获取插入到第一个孩子中的表单数据,并在提交表单时路由到的另一个孩子中使用它.
I want to take form data inserted in the first child, and use it in the other child which I route to upon submitting the form.
我怀疑我需要使用@input 或@output,但我找不到有关使用路由器插座时如何执行此操作的任何文档.
I suspect I need to use @input or @output but I can't find any documentation on how to do it when using the router-outlet.
我目前的其他解决方案是在第一个孩子提交表单并在第二个孩子中调用它时将数据保存在localstorage中.看起来不太理想.
My current other solution is to save the data in the localstorage when submitting the form in the first child and calling it in the second child. Doesn't seem ideal.
您可以通过服务传递数据.如果您创建一个服务,并在子 A 中设置数据,那么您可以从子 B 检索它.唯一的问题是您需要将您创建的此服务设置为父类的提供者,而不是子组件的提供者.
You could pass the data via a service. If you create a service, and set the data in child A, you could then retrieve it from child B. The only catch is you need to set this service you create as a provider for the parent class, and not for the child components.