Angular 2,一次从服务器加载数据并结果共享把组件的最佳实践
问题说明
使用服务在 Angular 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.
注意:
不要忘记在bootstrap函数中注册服务.深入观察代码.你会得到你想要的.路由部分不演示.Surf plunk 以供进一步实施
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.
}
}
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfhgfj
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20