Justin W Hall Justin W Hall - 5 months ago 22
AngularJS Question

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…

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 :

    <title>Angular QuickStart</title>


      System.import('app').catch(function(err){ console.error(err); });

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

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

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