简体   繁体   English

如何将值从node / express应用传递到AngularJS控制器

[英]how to pass a value from node/express app to an AngularJS controller

I'm developing an app based on mean.js boiler plate. 我正在开发基于mean.js样板的应用程序。

In one of my Angular controllers, I need to "know" whether the app is running in dev, test, or prod. 在我的一个Angular控制器中,我需要“知道”该应用程序是否正在开发,测试或生产中运行。

When the hosting Node app starts, this is indicated via the NODE_ENV environment variable, so Node knows where its running. 启动托管Node应用程序时,这通过NODE_ENV环境变量指示,因此Node知道其运行位置。

How do I pass this knowledge onto the Angular part of the app? 如何将这些知识传递到应用程序的Angular部分?

If you have this knowledge on your backend, why not make an endpoint you can call in an AngularJS run method. 如果您对后端有足够的了解,为什么不创建可以在AngularJS run方法中调用的终结点。 While I do not know the details of your backend implementation, surely you can return a variable which represents this information. 虽然我不知道您的后端实现的详细信息,但是您当然可以返回一个代表此信息的变量。 You can simply craft something like the following... 您可以简单地制作以下内容...

app.run(['$rootScope', '$http', function ($rootScope, $http) {
    $http.get('/yourEndoint').success(function(response) {
        $rootScope.whereAmI = response.whereAmI;
    });
}]);

Where wereAmI is some value you return from your backend and return to this call. wereAmI是您从后端返回并返回此调用的一些值。 If you place it on $rootScope , all other $scope 's will inherit this value so you'll have knoweldege of "where you're at" app wide. 如果将其放在$rootScope ,所有其他$scope都将继承此值,因此您将了解整个应用范围的“您所在的位置”。

For more info on the run function, check out the AngularJS module docs 有关run功能的更多信息,请查看AngularJS模块文档

Run blocks are the closest thing in Angular to the main method. 运行块是Angular中最接近main方法的。 A run block is the code which needs to run to kickstart the application. 运行块是启动应用程序所需运行的代码。 It is executed after all of the services have been configured and the injector has been created. 在配置完所有服务并创建了注射器后,将执行该命令。 Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests. 运行块通常包含难以进行单元测试的代码,因此,应在隔离的模块中声明它们,以便可以在单元测试中将其忽略。

In my case, I use gulp/grunt build task to select the requested config.js file (ie. production.config.js ). 就我而言,我使用gulp / grunt构建任务来选择请求的config.js文件(即production.config.js )。 Then you can use something like npm args to set an --env=production or --env=development variable when running your build task, which then is used by the gulp/grunt task to grab the requested config file. 然后,您可以在运行构建任务时使用类似npm args的设置--env=production--env=development变量,然后--env=development / grunt任务将其用于获取请求的配置文件。

Then your actual config file will just be an angular.constant(...) component with settings to use for your app. 然后,您的实际配置文件将只是一个angular.constant(...)组件,其中包含要用于您的应用程序的设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM