在Angular 2和Ionic 2中访问整个应用程序的关键数据

Dus*_*ilk 5 class typescript ionic2 angular

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

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

我实际上不知道围绕这个的最佳实践是什么,并且在这个主题上找不到多少.

tos*_*skv 9

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

服务:

import {Injectable} from 'angular2/angular2';


@Injectable()
export class Config {

  constructor() {}

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

}
Run Code Online (Sandbox Code Playgroud)

的Bootstrap:

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
Run Code Online (Sandbox Code Playgroud)

用法:

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);
  }
Run Code Online (Sandbox Code Playgroud)