Reputation: 1592
During the initial request, how can I load a user object (or any object) on an Express back-end and then populate an Angular app as soon as it is loaded? I have an application that I am sending a JWT token to. I have sucessfully validated the session and loaded the initial data (user object, etc.) that the application needs. I just cannot figure out how to load it with the Angular app.
Upvotes: 1
Views: 121
Reputation: 3730
Simplest thing would be to embed the JSON object as a global in the rendered page. If you are using Jade, it would look something like this
- hello = {"hello": 234}
script(type="text/javascript")
!= 'window.hello =' + JSON.stringify(hello) + ';'
So now the object is globally available at window.hello
, and you can access it from your angular code inside a <script src="..."></script>
Note: I strongly recommend against this, it could lead to spaghetti code. And even if it sounds delicious it's hard maintain. Instead I would suggest you completely decouple your angular app from the server side rendering. But if you are only using this technique for User information, I guess it's not too bad®.
Happy Coding!
Upvotes: 0
Reputation: 3931
in your template (generated server side) you can add something similar to this
<script>
angular.module('myConfig', [])
.value('jwt', {...});
</script>
then you can inject myConfig as a dependency of you angular app and you have access to jwt value within the app
angular.module('myApp', ['myConfig'])
.factory('myFactory', function($http, jwt){
return {};
});
Upvotes: 0
Reputation: 3088
Embed it in the page at the server side, perhaps using a templating engine.
See mean.js framework, it does something similar exactly that.
https://github.com/meanjs/mean/blob/master/app/views/layout.server.view.html
Upvotes: 0