问题描述
什么是存储(和共享)的初始值在使用服务的角度2应用程序的最佳做法?
我有从一个服务器是阵列和对象资源,配置和其它加载的数据量的服务。
我不想每次我打开一个组件或当我的路线图,我只是想用这些对象和数组已加载的时候,如果需要在应用程序启动,以及可选重装的时间来加载这些数据。
现在的问题是在哪里存储这个值,如何在正确的地方穿过使用该服务的组件共享?
谢谢你。
What is the best practice to store (and share) initial values in an Angular 2 application using a service?I have a service that loads much data from a server as resources,configurations and other that are array and objects.I do not want to load this data each time I load a component or when I route to a view, I just want to use these objects and array already loaded when the application starts, and optionally reload if needed.The question is where is the right place to store this values and how to share across components that use the service?Thanks.
推荐答案
您不得不考虑的共享服务并确保只有单个实例组件中共享。
结果
You have to think about shared service and make sure only single instance is shared among components.
的注意的:结果不要忘记在引导函数来注册服务。观察code深。你会得到你想要的东西。路由部分不证实。进一步落实冲浪普拉克
Note:
don't forget to register service in bootstrap function. Observe code deeply. you will get what you want. Routing part is not demonstrated. Surf plunk for further implementation
service.ts
import {Component, Injectable,Input,Output,EventEmitter} from 'angular2/core'
import {Router} from 'angular2/router';
import {Http} from 'angular2/http';
export interface Info {
name:string;
}
@Injectable()
export class NameService {
constructor(http:Http;router:Router)
{
this.http=http;
// you can call server resource from here and store it down to any variable.
}
info: Info = { name : "Jack" };
change(){
this.info.name = "Jane"; // this.info is shared among components.
}
}
这篇关于角2,最佳实践是从服务器加载数据一次,并分享成果成分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!