Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

class - Access key data across entire app in 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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...