ExpressJS variables in AngularJS - Mean Stack

2020-07-22 18:55发布

问题:

I am building a MEAN application, one issue I have is that I want to give my users some sort of control over the routes used. So I want my server side code (expressJS) to set some variables in my client side code.

Essentially I want to be able to generate my client side JS from my server side code.

for example, in PHP I would probably do something along the lines of

<?php
echo <script>
echo  var test = $test
echo </script>
 ?>

I am not talking about binding, the variables only need to be set at the initial application load.

What would be the best way to accomplish this kind of integration with MEAN, in the cleanest way possible...

回答1:

Just an other approch

router.js
app.get('/myconfig', function(req, res){
    var config = {prop1:1,myarray:[1,2,3]};
    var json = JSON.stringify(config);
    res.end('var config='+json);
});
jade
script(type='text/javascript', src='/myconfig')

than in angular you can do

angular.module('yourApp').constant('setup', config)


回答2:

Option 1

First write an api endpoint that will return your configurations.

app.get('/conf', function(req, res) {
    res.send(200, {
        foo: "bar"
    });
});

Then do a $http.get to this endpoint and retrieve the configuration object on angular app.run and store this configuration in a service/$rootScope/config.

app.run is the closest thing in angular to a main() function and will run once when the application starts.

Option 2

Use grunt.

If your solution does not need to explicitly get the variables from server side, and if they are known at the time you deploy the application, you can do a javascript compile and inject the configurations using grunt.

This is how I have personally handled this situation.



回答3:

My approach is a complete separation between client & server side.

A demo plunker: http://plnkr.co/edit/5cFLo3wLfbL0bUnifJe5?p=preview

The server should only be concerned with resources:

app.get('/api/setup', function(req,res){

  var setup = // something

  res.json(setup);
})

The client can defer bootstrap after fetching data:

Based on this answer: Using angular services before manual bootstrap

angular.bootstrap().invoke(function($http){ 

    $http.get('/api/setup').then(function(res){

        // providing the fetched data to the module:
        angular.module('yourApp').constant('setup', res.data)

        // manual bootstraping
        angular.bootstrap(document,['yourApp']);

    })
});

Then you can inject setup inside your module:

app.config(function(setup){
  // constants can be injected to config blocks
})

app.controller('ctrl',function(setup){
   // do what you need
})

If you need a splash screen check my answer: Creating a splash screen using ng-cloak