• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Angular 2,一次从服务器加载数据并结果共享把组件的最佳实践

用户头像
it1352
帮助1

问题说明

使用服务在 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.

正确答案

#1

你必须考虑共享服务并确保只有单个实例在组件之间共享.

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
系列文章
更多 icon
同类精品
更多 icon
继续加载