Angular 2 Universal - Store Global Variables

前端 未结 1 994
半阙折子戏
半阙折子戏 2021-01-22 02: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

相关标签:
1条回答
  • 2021-01-22 03:02

    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';
        }
    
    0 讨论(0)
提交回复
热议问题