0

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…

3 Answers 3

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Instead of just using global window inside a service, their are some discussions about the right way to inject window in a more "angular way". See stackoverflow.com/questions/34177221/…
0

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)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.