AngularJS : Initialize service with asynchronous data

后端 未结 10 1920
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 03:09

I have an AngularJS service that I want to initialize with some asynchronous data. Something like this:

myModule.service(\'MyService\', function($http) {
            


        
10条回答
  •  Happy的楠姐
    2020-11-22 03:31

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

提交回复
热议问题