简体   繁体   中英

Pass json object on page to Angular2 component

I understand that services are the preferred way to get data into an app. However, what it the data is already on the page as js variable. Essentially looking for how you'd do the following with Angular:

var foo = {key1:value2, key2:value2};

myInitFunction( foo );

// This function may be on the page or in an external doc
myInitFunction( foo ){
// Do stuff with foo… 
}

Essentially, foo exists on page load as a server-side object already. It seems silly to me to make an Ajax call to get this information (again). Foo could exist elsewhere like:

<span data-foo="{key1:value2, key2:value2}}></span>

If that makes getting the data into my app easier…

An easy way to do it is to store it as a global variable in your index.html for example :

<html>
  <head>
    <title>Angular QuickStart</title>

    <!-- BASIC ANGULAR 2 INDEX HTML -->

    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>
  <body>
    <my-app>Loading...</my-app>

    <script>
        // Store your value in some global scope variable.
        window.foo = {key1:'value2', key2:'value2'};
    </script>
  </body>
</html>

And then, you can wrap this value in some Angular2 service

@Injectable()
export class FooService {
    getFoo() {
        return window.foo;
    }
}

I assume this span is on your initial html page when you bootstrap your app(main) module, if so then you can do some jquery and assign this value to a global variable. (such as

var meyVar = $('#mySpan').attr('data-foo')

) and then in your angular component you declare myVar and you can access it.

declare _myVar;
alert(_myvar)

I think the solution would be a custom value provider, then you can use dependency injection with it within your application. Check out: https://angular.io/docs/ts/latest/guide/dependency-injection.html

In your index.html:

<script>
  window.config = {key1:value2, key2:value2};
</script>

And then in your app.module

import { OpaqueToken } from '@angular/core';
export let APP_CONFIG = new OpaqueToken('app.config');
/* ... */
@NgModule({  
    /* ... */
    providers: [{ provide: APP_CONFIG, useValue: window.config }]
})
class AppModule {}

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