角度2:跨不同路线共享数据 [英] Angular 2: sharing data across different routes

查看:70
本文介绍了角度2:跨不同路线共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在SO中搜索了类似的问题,但没有找到任何可以解决我的具体情况的问题.有很多技术可以在角度组件之间共享数据,我已经阅读了有关组件通信的这篇文章: https://angular.io/docs/ts/latest/cookbook/component-communication.html

I have searched for similar questions in SO and I have not found any that addresses my specific case. There are many techniques to share data between angular components, and I have read this article about component communication: https://angular.io/docs/ts/latest/cookbook/component-communication.html

但是,这里描述的技术都不适合我,因为我的组件位于不同的路径上.本文主要介绍父子组件的通信,并且在某些情况下,只要两个组件同时加载,它们可能对兄弟组件起作用.

However none of the techniques described there work for me, because my components are on different routes. The article describes mostly parent-child component communication, and some cases may work for sibling components as long as they are both loaded at the same time.

我的案例与Angular 2 Heros教程非常相似:我有一条路线显示一个包含客户列表的表格(而不是英雄).当用户单击特定客户时,我触发了路由更改,以显示包含所选客户(而不是英雄)数据的表单.

My case is very similar to the Angular 2 Heroes tutorial: I have a route that displays a table with a list of customers (instead of heroes). When the user clicks on a specific customer, I trigger a route change to display a form with the data for the selected customer (instead of hero).

英雄教程执行服务调用以检索选定的英雄数据,但是鉴于那些数据已经在内存中,因此我想避免一个无用的附加AJAX调用.我只想将所选的客户数据传递给客户表单组件,以便立即显示它.

The heroes tutorial performs a service invocation to retrieve the selected hero data, but I want to avoid a useless additional AJAX call, given that those data are already in memory. I just want to pass the selected customer data to the customer form component so it is immediately displayed.

我正在考虑一个全局会话"服务,可以在其中存储和检索想要的任何对象,但是我不确定这是一个好主意.还有其他更适当的方法吗?

I am thinking of a "global session" service where I could store and retrieve any object I want, but I am not sure this is a good idea. Are there other more adequate approaches?

推荐答案

使用主应用程序文件提供的服务,然后在您希望获取/设置整个应用程序中可用的数据时将其注入

use service that is provided by main application file and then inject it whenever you want to get/set data that will be available in whole app

main.app.ts

main.app.ts

@Component({
...
  providers:[yourDataService]
...
})

其他组件

import {yourDataService} from '...';

@Component({
...
providers:[]// we must use provider from main file
...
})
export class someComponent{

  contructor(private myData:yourDataService){}

}

使用主应用程序文件中的提供程序非常重要,因为如果您在每个组件中提供服务,则将有另一个服务实例,当然每个服务中也会有不同的数据

it is important to use provider from main app file because if you provide service in each component you will have another instances of your service and of course different data in each service

您还可以使用 observables 进行通知当某些数据更改时

you can also use observables to be notified when some data has changed

有关更多信息,请参见分层注入树注入器

for more info look at hierarchical injections or tree injector

这篇关于角度2:跨不同路线共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆