问题
I am trying to convert my AngularJS application to Angular 2 Universal application (because of server-side rendering).
https://github.com/angular/universal-starter
Now I need to store global variables which could be achieved easily in normal Angular 2 applications(per below links).
Angular 2 global variable
Angular 2 - Whats the best way to store global variables like authentication token so all classes have access to them?
One thing you will have to do to achieve this in normal angular 2 App is to pass your global service to bootstrap.
I don't think you can do that in Angular 2 universal app unless I am missing something.
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
How can I store global variables in Angular 2 Universal App?
Thanks Fahad Mullaji
回答1:
This is another way to use Method 1 of my answer at https://stackoverflow.com/a/39031152/1810391
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(assume this is your root module)
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';
}
来源:https://stackoverflow.com/questions/39552388/angular-2-universal-store-global-variables