问题描述
我正在尝试将我的 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).
Angular 2 -存储身份验证令牌等全局变量以便所有类都可以访问它们的最佳方法是什么?
要在普通的 angular 2 应用程序中实现这一点,您必须做的一件事是将您的全局服务传递给引导程序.
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 中的Session 数据一样.而且这需要在不制作父子组件的情况下完成
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 通用应用中存储全局变量?
How can I store global variables in Angular 2 Universal App?
谢谢法赫德·穆拉吉
推荐答案
这是另一种使用我在 https 上回答的方法 1 的方法://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 - 存储全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!