Access key data across entire app in Angular 2 & Ionic 2

前端 未结 3 1177
独厮守ぢ
独厮守ぢ 2020-12-11 06:27

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

For user information my initial thought was to

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-11 07:09

    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.

    Service:

    import {Injectable} from 'angular2/angular2';
    
    
    @Injectable()
    export class Config {
    
      constructor() {}
    
      public get USERID(): string {
          return "XCAMPLISHIOUS";
      }
    
    }
    

    Bootstraping:

    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
    

    Usage:

    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);
      }
    

提交回复
热议问题