Justin W Hall
Justin W Hall

Reputation: 371

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…

Upvotes: 0

Views: 784

Answers (3)

Stefan Negele
Stefan Negele

Reputation: 1112

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 {}

Upvotes: 0

Aran Dekar
Aran Dekar

Reputation: 481

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)

Upvotes: 0

No&#233;mi Sala&#252;n
No&#233;mi Sala&#252;n

Reputation: 5036

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

Upvotes: 1

Related Questions