在 Angular 2 & 中访问整个应用程序的关键数据离子 2 [英] Access key data across entire app in Angular 2 & Ionic 2

查看:10
本文介绍了在 Angular 2 & 中访问整个应用程序的关键数据离子 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Angular 2 和 Ionic 2 中存储我可以在整个应用程序中访问的数据的最佳方式是什么 - 打字稿.

What would be the best way to store data that I can access across an entire app in Angular 2 and Ionic 2 - typescript.

对于用户信息,我最初的想法是在所需的每个文件中导入 User 类,但由于我需要一个用户 ID,我认为最好有某种配置文件,也许App 类 - 我还可以存储环境信息和 url 等.

For user information my initial thought was to just import the User class in every file its needed, but since all I require from there is a user ID I thought it'd be better to have some kind of config file, maybe the App class - and I could store environment information as well and urls ect.

我实际上不知道围绕这个的最佳实践是什么,也找不到关于这个主题的太多内容.

I actually have no idea what the best practice around this is and couldn't find much on the topic.

推荐答案

一种方法是使用您需要的所有属性创建类,并在引导应用程序时配置为单例.

One way to do it would be to make class with all the properties that you need and configure as a singleton when you bootstrap the application.

服务:

import {Injectable} from 'angular2/angular2';


@Injectable()
export class Config {

  constructor() {}

  public get USERID(): string {
      return "XCAMPLISHIOUS";
  }

}

引导:

import {bootstrap} from 'angular2/angular2';
import {TaciIlieApp} from './app/taci-ilie';
import {Config} from './app/services/config/config';

bootstrap(TaciIlieApp, [Config]); // configuring the Config provider here will ensure a single instance is created

用法:

import {Component, Inject} from 'angular2/angular2';

import {Config} from '../../services/config/config';

@Component({
  selector: 'game',
  templateUrl: 'app/components/game/game.html',
  styleUrls: ['app/components/game/game.css'],
  providers: [],
  directives: [],
})
export class Game {


  constructor(private config: Config) {
      console.log(this.config.USERID);
  }

这篇关于在 Angular 2 & 中访问整个应用程序的关键数据离子 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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