在 Angular 2 和 Ionic 2 - typescript 中存储我可以在整个应用程序中访问的数据的最佳方式是什么。
对于用户信息,我最初的想法是只在每个需要的文件中导入 User 类,但由于我只需要一个用户 ID,我认为最好有某种配置文件,也许是应用类 - 我还可以存储环境信息和 url 等。
我实际上不知道围绕此的最佳实践是什么,也找不到太多关于该主题的信息。
最佳答案
一种方法是创建具有您需要的所有属性的类,并在您引导应用程序时将其配置为单例。
服务:
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);
}
关于class - 在 Angular 2 和 Ionic 2 中访问整个应用程序的关键数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34815478/