如何在注射前更改Angular工厂以解决

时间:2017-05-10 11:18:07

标签: javascript angularjs dependency-injection angular-factory

我有一个使用MapProvider的现有应用程序,如下所示:

mapModule.factory('MapProvider', ['$injector', function($injector) {
    return $injector.get('GoogleMapsService');        
}]);

此MapProvider广泛应用于整个应用程序,并被注入各种其他控制器和服务(正确或错误)。

我现在需要添加一个BaiduMapsService,我已经能够将其作为测试用于:

mapModule.factory('MapProvider', ['$injector', function($injector) {
    if(true) {
        return $injector.get('GoogleMapsService');
    } else {
        return $injector.get('BaiduMapsService');
    }
}]);

相应地翻转if值。 (这两种服务都使用TypeScript接口,因此具有相同的方法)。现在,我需要向API添加$http调用,该调用将根据提供的数据返回要使用的地图。如何让我的工厂异步,不用将所有MapProvider.someCallHere()次来电更改为MapProvider.then(m => m.someCallHere())

理想情况下,当在我的应用程序中注入MapProvider时,它将能够使用异步数据解析(仅一次),然后注入必要的服务。

或者,有没有办法推迟/延迟加载Angular,直到我进行API调用并在某处设置一些全局数据?

感谢。

2 个答案:

答案 0 :(得分:2)

您可以推迟申请bootstrap(也不要使用ng-app,手动执行),直到您从服务器获取数据。我之前已就此question回答了这个问题,但每个案例都有自己的具体细节。

我经常看到在应用程序被引导之前在应用程序上声明了配置值,这对于多租户应用程序非常有用。这样,这个首选项值可以作为注入的提供者在整个应用程序中使用。

例如:

var app = angular.module('app', []);

// retrieve the $http provider
var ngInjector = angular.injector(["ng"]);
var $http = ngInjector.get("$http");

// load config function. Returns a promise.
function loadConfig(){
    return $http.get("/config.json").then(function(response) {
        // declare the configuration value on your app
        app.constant("Config", response.data);
    }, function(err) {
        console.error("Error loading the application config.", err)
    });
}

// Call loadConfig then bootstrap the app
loadConfig().then(function () {
    angular.element(document).ready(function() {
        angular.bootstrap(document, ["app"]);
    });
});

最后,从您的工厂,您可以使用Config常量来检索首选地图。

mapModule.factory('MapProvider', ['$injector', 'Config', function($injector, Config) {
    if(Config.preferedMap == 'GoogleMap') {
        return $injector.get('GoogleMapsService');
    } else {
        return $injector.get('BaiduMapsService');
    }
}]);

答案 1 :(得分:0)

我能想到的唯一方法就是初始化整个angular(和模块),直到得到“config”(并设置为全局变量)。