简体   繁体   中英

How all components & services can access Web.Config Keys defined in web.config of MVC+Angular5 Project

I have MVC + Angular 5 application and some app-keys defined in web.config. I am able to access the keys in Index.cshtml file uisng the below code:

<script type="text/javascript">
    var webConfigKeyValues = new Object();
    webConfigKeyValues = @Html.Raw(Json.Encode(ViewBag.WebConfigKeyValues));
</script>

<app-root></app-root>

My Angular 5 app consists of multiple feature modules. How can I access webConfigKeyValues in all feature modules, components, and services

That's not possible. Angular is a client-side framework, and from the browser it is not possible to access the web.config.

On the other hand, you can create some user control in MVC and add that in every cshtml file.

As an alternative to my answer in this post , which describes how to reference a global variable directly or via a decorator , it is also possible to use an InjectionToken to get the values you passed to the JavaScript scope. ( Demo )

You can define the token as following

export const MY_WEBCONFIG_TOKEN = new InjectionToken<any>('Data from cshtml',   
{
    providedIn: 'root',
    factory: () => window["webConfigKeyValues"]
});

And then Inject that token into the components and services that rely on that data.

@Component({
    ...
})
export class AppComponent {
    constructor(
        @Inject(MY_WEBCONFIG_TOKEN) private token: any
    ) { }
}

EDIT

For Angular version 5.x you need to use a ValueProvider ( Docs ) to assign a value to an InjectionToken .

export const MY_WEBCONFIG_TOKEN = new InjectionToken<any>('Data from cshtml',);

*.module.ts

@NgModule({
    ...
    providers: [
        { provide: MY_WEBCONFIG_TOKEN, useValue: window["webConfigKeyValues"] }
    ]
    ...
}})
export class MyModule { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM