简体   繁体   中英

OS environment variables in Angular

I know about the environment.ts files in Angular, but with those I end up comitting sensitive data to my git repo. In Java I can just refer to OS environment variables which I can set on my server.

In our company the CI dockers all our applications and pushes them into OpenShift, which means I don't have access to the file system, so I can not just put a production environment.ts there manually.

Does anyone have an idea how to get to the OS environment variables?

If you are bundling your angular application with webpack, you can use webpack.DefinePlugin .

plugins: [
    new webpack.DefinePlugin({
        "some_variable": JSON.stringify(process.env.SOME_ENV_VAR || "my_default_value")
    })
]

Then you can reference "some_variable" in your angular application. You can declare them in your typings.d.ts file so they are recognized.

declare const some_variable: string

You can always have a web service that can serve you these variables through api calls as well.

  1. Have an API that serves the config, and retrieve that from angular

    app.get("/api/config/default", function(req, res) { res.send({ a: process.env["A_VAR"] }); })
  2. Have your back-end generate the angular constants

    app.get("/generated-config.js", function(req, res) { res.send( "angular.module('myApp').constant('MY_CONFIG'," + "{'a': \\"" + process.env["A_VAR"] + "\\"" + "})" ); });

    For which you can use ng-constant . I like this approach better because blocking angular controllers and services that depend on this config becomes very easy. In my case, the back-end generates this file and serves it together with the rest of the static files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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