Angular 2 Universal - Store Global Variables

坚强是说给别人听的谎言 提交于 2019-12-02 07:11:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!