Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Universal - Store Global Variables

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

like image 562
Fahad Mullaji Avatar asked Apr 17 '26 12:04

Fahad Mullaji


1 Answers

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';
    }
like image 124
John Siu Avatar answered Apr 20 '26 02:04

John Siu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!