Pass Constant Values to Angular from _layout.cshtml

前端 未结 3 486
无人及你
无人及你 2021-01-05 17:52

Okay, so I have a constant variables in the _Layout.cshtml of ASP.Net SPA project and I would to pass them so that Angular will have access to those.

How can I do t

3条回答
  •  暖寄归人
    2021-01-05 18:18

    The first answer above was my favorite if you are using JIT compilation. We are using JIT for development and AOT for deployment. I couldn't find a good way to make the first answer work with AOT. For reference I followed the AOT cookbook here... Angular AOT cookbook.

    The approach below will not work for server side rendering but should suffice for both JIT and AOT client side rendering.

    1) In the razor view, _layout.cshtml for example, just put a script block and set a JSON object on the window interface. I placed this block within the "head" tag but doesn't really matter. The values for the JSON keys can be determined by any razor syntax.

    2) Create an app context service and wire up in appropriate module and inject into components for usage, if you need help with this just comment and I'll supply more info.

    import { Injectable } from '@angular/core';
    
    /*
        must match definition in SCRIPT tag that is seeded from razor
    */
    interface IAppContext {
        userName: string;
    
        isAdmin: boolean;
    }
    
    /*
        
    */
    @Injectable()
    export class AppContextService implements IAppContext {
    
        userName: string;
    
        isAdmin: boolean;
    
        constructor() {
            var appContextBootstrap: IAppContext = ((window).appContext);
    
            this.userName = appContextBootstrap.userName;
            this.isAdmin = appContextBootstrap.isAdmin;
        }
    
    }

    3) reference and use the app context service throughout the application.

    import { Component } from '@angular/core';
    
    import { AppContextService } from './appContext.service'
    
    @Component({
        moduleId: module.id,
        selector: 'story-app',
        templateUrl: 'app.component.html'
    })
    export class AppComponent {
        AppConfig: any;
        constructor(private appContext: AppContextService) { }
    
        ngOnInit() {
    
            alert('hi - ' + this.appContext.userName);
        }
    }

提交回复
热议问题