0

In my angular app, I have a URL to which I connect for retrieving some data, a CORS enabled server.

Now, so far I had it hardcoded in my javascript file:

server_url = "http://localhost:7888/api.php/json?id=2"

Now, on test and production, those URLs of course are not valid...and everytime I do a git pull it overrides my customizations.

Where would I elegantly put a config like that in an angular app?

4

2 回答 2

0

好吧,基本上我会在这里采用 mean.js 方法,它很容易实现,并且对您或其他任何人都可能有用。

你必须从你的中间件以角度写入你的主 HTML 文件(例如:index.html),在你的情况下,你的端点的 URL 必须根据你的环境而改变,只是为了保持简单假设我们有 dev (本地主机)和生产 (mydomain.com)

在你的索引 html 中做一个简单的写:

 <script type="text/javascript">
        <?php 
         if(strpos( $_SERVER['HTTP_HOST'], 'mydomain.com') !== false){
             print "var endpoint = '"+ $server_url+ "';" 
         } else{
            print "var endpoint = '"+ $local_url+ "';" 
         }

         ?>
    </script>

一个你把它放到你的主 index.html 中,它可以通过使用 window 对象以角度形式使用,所以你可以将它包装成一个 constant 或一个service

这是常量的示例:

angular.module('app').run(function () {

}).value('endpoint', window.endpoint);

我不精通PHP,但我希望你能明白我的意思

于 2014-11-13T20:19:51.033 回答
0

将其声明为常数。假设您有一个名为的应用程序App

angular.module('App', []).constant("urls", {"server_url":"http://localhost:7888/api.php/json?id=2"});

一旦声明为常量,您就可以将其作为依赖项注入,就像您注入服务一样。

于 2014-11-13T17:21:06.040 回答