首页 文章

如何基于域或主机应用程序动态更改Angularjs服务上的API endpoints

提问于
浏览
1

我有使用Angularjs和Web API的MVC Web应用程序,这两个应用程序都发布在不同的域中 . 每次我提交代码更改时,TFS都会发布MVC应用程序和Web API,并使用web.config转换它会更改Web配置连接和应用程序密钥以指向开发人员, 生产环境 或测试 .

现在我正在使用angular我有一个服务,指向API endpoints 做一些事情,例如登录 .

...

function loginService($http, $q) {

        var baseUri = "http://localhost/"

        var service = {
            login: login,
           ...
        };

        return service;


        function login(user, password) {
            var deferred = $q.defer();
            $http({ method: 'POST', url: baseUri + '/api/tokens',
...

正如您所看到的,baseUri设置为localhost但我希望它对于 生产环境 环境类似 var baseUri = "http://production/" 和测试 baseUri = "http://testing/" . 所以baseUri的变化取决于TFS发布的内容 .

请记住,托管MVC应用程序的域与WebAPI不同,因此我无法检查角度范围的域并构建基URI .

谢谢

2 回答

  • 3

    你可以在MVC应用程序的域上进行切换,并根据它构建API的URI来进行切换吗?

    所以类似于:

    switch (MVCdomain) {
        case "http://production/": baseUri = "http://APIproduction/"; break;
        case "http://testing/": baseUri = "http://APItesting/"; break;
    }
    

    可能会将其封装在自己的endpointService中,您可以将其注入loginService或任何其他需要它的服务,如下所示:

    (function () {
        angular.module('app').factory('endpointService', function ($location) {
            return {
                getAPIEndpoint: function () {
                    var endpoint = '';
                    switch ($location.host()) {
                        // test if MVC app is in prod/test/local and determine what API endpoint should be called
                        case 'ProdDomainP.com': endpoint = 'ProdDomainAPIP.com'; break;
                        case 'TestDomainP.com': endpoint = 'TestDomainAPIP.com'; break;
                    }
                    return endpoint;
                }
            }
        });
    })();
    

    这将是您注入其他服务的服务,以确定您调用的API endpoints ,如下所示:

    function loginService($http, $q, endpointService) {
    
        var baseUri = endpointService.getAPIEndoint();
    
        var service = {
            login: login,
           ...
        };
    
        return service;
    
    
        function login(user, password) {
            var deferred = $q.defer();
            $http({ method: 'POST', url: baseUri + '/api/tokens',
        ...
    
  • 0

    我也想尝试这样做 . 所以我没有在我的角度应用程序中硬编码api endpoints ,在我引导角度之前,我在JavaScript中进行服务调用以获取 endpoints . 在服务器端(web api),控制器从web.config读取以获取角度应用程序将使用的 endpoints 并将它们作为JSON返回 . 然后,在我引导角度之前和 endpoints 返回到JavaScript之后(通过本机js promise或角度承诺),我设置了一个包含所有 endpoints 的全局对象var . 在角度中,有一个 endpoints 服务公开此全局 endpoints 对象 . 最后,当设置 endpoints 对象时,我引导角度应用程序 . 这可以确保在角度运行之前设置 endpoints 并尝试使用 endpoints .

    它很糟糕,需要有一个存在于角度之外的全局 endpoints 对象,但这是我能想到的唯一方法,允许使用web.config进行转换,而不必在js中对URL endpoints 进行硬编码

相关问题