I have an AngularJS service that I want to initialize with some asynchronous data. Something like this:
myModule.service(\'MyService\', function($http) {
So I found a solution. I created an angularJS service, we'll call it MyDataRepository and I created a module for it. I then serve up this javascript file from my server-side controller:
HTML:
Server-side:
@RequestMapping(value="path/myData.js", method=RequestMethod.GET)
public ResponseEntity getMyDataRepositoryJS()
{
// Populate data that I need into a Map
Map myData = new HashMap();
...
// Use Jackson to convert it to JSON
ObjectMapper mapper = new ObjectMapper();
String myDataStr = mapper.writeValueAsString(myData);
// Then create a String that is my javascript file
String myJS = "'use strict';" +
"(function() {" +
"var myDataModule = angular.module('myApp.myData', []);" +
"myDataModule.service('MyDataRepository', function() {" +
"var myData = "+myDataStr+";" +
"return {" +
"getData: function () {" +
"return myData;" +
"}" +
"}" +
"});" +
"})();"
// Now send it to the client:
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "text/javascript");
return new ResponseEntity(myJS , responseHeaders, HttpStatus.OK);
}
I can then inject MyDataRepository where ever I need it:
someOtherModule.service('MyOtherService', function(MyDataRepository) {
var myData = MyDataRepository.getData();
// Do what you have to do...
}
This worked great for me, but I am open to any feedback if anyone has any. }