Angular 2 Universal-存储全局变量 [英] Angular 2 Universal - Store Global Variables
问题描述
我正在尝试将AngularJS应用程序转换为Angular 2 Universal应用程序(由于服务器端渲染).
I am trying to convert my AngularJS application to Angular 2 Universal application (because of server-side rendering).
https://github.com/angular/universal-starter
现在,我需要存储可以在普通Angular 2应用程序中轻松实现的全局变量(按下面的链接).
Now I need to store global variables which could be achieved easily in normal Angular 2 applications(per below links).
角度2-存储诸如身份验证令牌之类的全局变量的最佳方法是什么,以便所有类都可以访问它们?
要在普通的angular 2应用中实现这一目标,您要做的一件事就是将全局服务传递给Bootstrap.
One thing you will have to do to achieve this in normal angular 2 App is to pass your global service to bootstrap.
除非我缺少某些东西,否则我认为您无法在Angular 2通用应用程序中做到这一点.
I don't think you can do that in Angular 2 universal app unless I am missing something.
我想存储用户数据并在整个应用程序中使用它.就像asp.net中的会话数据一样.而且,这需要在不制作父子组件的情况下完成
I want to store user data and use it across application. Just like Session data in asp.net. And plus this needs to done without making parent-child components
如何在Angular 2 Universal App中存储全局变量?
How can I store global variables in Angular 2 Universal App?
谢谢 法赫德·穆拉吉(Fahad Mullaji)
Thanks Fahad Mullaji
推荐答案
这是在 https ://stackoverflow.com/a/39031152/1810391
要共享通用的数据结构,只需在所有组件中使用像global
这样的硬编码索引即可.
To share a common data structure, just use a hard-coded index like global
in all components.
globaldata.service.ts
import { Injectable } from '@angular/core';
interface ShareObj {
[id: string]: any;
}
@Injectable()
export class GlobalDataService {
shareObj: ShareObj = {};
}
app.module.ts(假设这是您的根模块)
import { GlobalDataService } from './globaldata.service';
//
// skip ..
//
@NgModule({
//
// skip ..
//
provider:[GlobalDataService]
})
export class AppModule {}
any.component.ts
code:
import { GlobalDataService } from './globaldata.service';
//
// skip ..
//
constructor(private gd: GlobalDataService){
// This can be string, array or object
this.gd.shareObj['global']='data';
}
这篇关于Angular 2 Universal-存储全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!