Angular2: inject server side config into service

前端 未结 3 1614
北荒
北荒 2021-01-27 01:27

I\'m using Angular 2.0.0 with TypeScript in ASP.NET Core. My goal is to create AppConfig service in my app, based on server-side variables. With a help from few other answers, I

3条回答
  •  滥情空心
    2021-01-27 01:54

    I ended up adding object to globals.

    // ===== File globals.ts

    import { AppConfig } from './app.config';
    'use strict';
    export var appConfig: AppConfig;
    

    // ===== File app.config.ts

    import { Injectable } from "@angular/core";
    @Injectable()
    export class AppConfig {
        entityId: string;
        formId: string;
    }
    

    // ===== File index.html or cshtml

    
    

    // ===== File main.ts

    import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
    
    import { AppModule } from './app.module';
    import { AppConfig } from './app.config';
    import myGlobals = require('./globals');
    
    //platformBrowserDynamic().bootstrapModule(AppModule);
    
    export function RunApplication(config: Object) {
    
        var appConfig = new AppConfig();
        appConfig.entityId = config["entityId"];
        appConfig.formId = config["formId"];
    
        console.log('Created config: ', appConfig, appConfig.entityId, appConfig.formId);
    
        myGlobals.appConfig = appConfig;
    
        platformBrowserDynamic()
            .bootstrapModule(AppModule)
            .catch(err => console.error(err));
    }
    

    // ===== File app.module.ts

    import { AppConfig } from './app.config';
    import myGlobals = require('./globals');
    ...
    
    @NgModule({
        imports: [
            ...
        ],
        declarations: [
            ...
        ],
        providers: [
            {
                provide: AppConfig,
                useValue: myGlobals.appConfig
            }
        ],
        bootstrap: [AppComponent]
    })
    

    // ===== File intro.component.ts

    import { AppConfig } from "./app.config";
    import myGlobals = require('./globals');
    @Component({
        selector: 'my-intro,[my-intro]',
        templateUrl: ''
    })
    export class IntroComponent {
        constructor() {
            console.log('constructor', 'appConfig', myGlobals.appConfig);
        }
    }
    

提交回复
热议问题