Justin W Hall Justin W Hall - 1 month ago 7
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…
}


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…

Answer

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;
    }
}
Comments