简体   繁体   English

在两个组件之间共享数据 Angular 7

[英]Sharing data between two components Angular 7

Hi all and thanks for your time!大家好,感谢您的时间!

I am creating a website with angular 7 and routing.我正在创建一个带有 angular 7 和路由的网站。 In one component, that shows home(default view), i have an input that asks person for name.在一个显示主页(默认视图)的组件中,我有一个输入要求人们输入姓名。

I want to pass this data to my other component.我想将此数据传递给我的其他组件。 After googling for a long time, i found out i should use services but is it really only option to share data?在谷歌搜索了很长时间后,我发现我应该使用服务,但它真的是共享数据的唯一选择吗? Anyone got an example of this?有人有这方面的例子吗?

ps: One answer on stackoverflow says "you can use a shared service(using observable) or you can use ngrx/store." ps:stackoverflow 上的一个答案说“您可以使用共享服务(使用 observable)或者您可以使用 ngrx/store。”

You can learn angular features from technical documentation https://angular.io/docs您可以从技术文档https://angular.io/docs 中学习角度特性

You can share data on a couple of ways depending on expectations and logic:您可以根据期望和逻辑以多种方式共享数据:

  • Parent/child components can use @Input in child component if you want to send object from parent to child component, @Output if you want to send an event from child to parent (this event can bring data)父/子组件如果要将对象从父组件发送到子组件,可以在子组件中使用@Input,如果要从子组件向父组件发送事件,则可以使用@Output(此事件可以带数据)
  • You can use event emitter with @Injectable service in the same angular module您可以在同一个 angular 模块中将事件发射器与 @Injectable 服务一起使用
  • You can use local storage and session storage if you want to save data on a client如果要在客户端上保存数据,可以使用本地存储和会话存储
  • You can use HTTP or WebSockets if you want to save data on a server如果你想在服务器上保存数据,你可以使用 HTTP 或 WebSockets

For now, I managed to do it using local storage so it works.现在,我设法使用本地存储来完成它,因此它可以工作。 Still i will need to dive deep into passing data these days to understand it better when it comes to getter and setter.这些天我仍然需要深入研究传递数据,以便在涉及 getter 和 setter 时更好地理解它。 for now it looks like this: component 1 HTML:现在它看起来像这样:组件 1 HTML:

<button (click)="saveData($event)" class="btn btn-outline-secondary" type="button"
            id="button-addon2">Send</button>

component 1 ts:组件 1 ts:

 saveData(){ localStorage.setItem('visitor', this.visitor);}

component 2 ts:组件 2 ts:

visitor = localStorage.getItem('visitor');

maybe someone will find it to be useful.也许有人会发现它很有用。

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

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