Angular 2,一次从服务器加载数据并将结果共享给组件的最佳实践 [英] Angular 2, best practice to load data from a server one time and share results to components

查看:17
本文介绍了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.

  }
} 

这篇关于Angular 2,一次从服务器加载数据并将结果共享给组件的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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