我正在尝试将我的AngularJS应用程序转换为Angular 2 Universal应用程序(因为服务器端呈现)。
https://github.com/angular/universal-starter
现在我需要存储全局变量,这些变量可以在普通的Angular 2应用程序中轻松实现(以下链接)。
在普通的角度2应用程序中,您必须做的一件事就是将您的全局服务传递给bootstrap。
我不认为你可以在Angular 2通用应用中做到这一点,除非我遗漏了什么。
我想存储用户数据并在整个应用程序中使用它。就像asp.net中的Session数据一样。而且这需要在不制作父子组件的情况下完成
如何在Angular 2 Universal App中存储全局变量?
由于 法赫德穆拉吉
答案 0 :(得分:10)
这是在https://stackoverflow.com/a/39031152/1810391
使用我的答案的方法1的另一种方法要共享公共数据结构,只需在所有组件中使用类似global
的硬编码索引。
<强> 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';
}