简体   繁体   中英

How to read a value from Viewbag in Angular2/ TypeScript?

I am using MVC and Angular2 for a web application. I need to pass a value from My Controller to the Index page, from where the Angular2 kicks in. Now I need to read the value in View bag from the angular using Typescript. Can I do that? I have searched a lot but didn't get any info!

You basically have two options.

Options #1: GET request

Make GET request from the root component (using service) which would fetch necessary configuration data.

Options #2: Embed JSON payload

With this option you can embed JSON data directly into the landing page. In order to be able to access this data from the Angular app, you need to store it as global variable. Then retrieving data object from the app would be pretty simple. The only thing, you should avoid reading global variables directly in this case, simply because it's error prone. It's better to abstract global access with simple AppConfig service. The benefit is that later you could change data source (if you decide to switch to GET-request option above) without much hastle.

So the first step is to write JSON into HTML, maybe like this:

<script>
  var __appConfig = JSON.parse('@Html.Raw(appConfig)');
</script>

I'm not C# expert so it may be not optimal.

Then helper service could look something like this:

export class AppConfig {
  private _config = window.__appConfig

  getConfig() {
    return this._config
  }
}

Which one to choose? I would say it depends on the kind of data you want to pass to Angular 2 app. In many cases with big JSON payloads it really makes sense to go with GET request way. On the other hand, for simple variables or small chunks of data I would prefer embedding data straight into the HTML. It would also save you from making one more AJAX request.

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