在Angular中配置提供程序时设置具有依赖性的函数

时间:2015-11-03 17:54:11

标签: angularjs

我想开发一个具有可配置paramsFnparamsFn的通用翻译器组件。这里paramsFn可以是普通函数,也可以是具有服务依赖性的函数。 (function () { "use strict"; angular.module("translator-app", []) .provider(translatorProvider); function translatorProvider() { var url, paramsFn; //Provider Config Functions function setUrl (pUrl) { url = pUrl }; function setParamsFn (pParamsFn) { paramsFn = pParamsFn; }; function factory ($http, $q) { //Service Function Pseudo function translate(key) { if (translateions are cached) { //return promis of cached translations } else { /* make http call with configured url and paramsFnto fetch translations. Cache translations. Return promise with translations. */ } } //translate //Service Object return { translate: translate }; } // factory factory .$inject = [ "$http" "$q" ]; //Exposed functionality this.setUrl = setUrl; this.setParamsFn = setParamsFn; this.$get = factory; } }(); 预计将返回一个承诺。

translator

应用程序在配置后可以使用paramFn。用户应用程序提供的将能够为paramFn提供服务依赖性。稍后在调用translator.translate(...)方法时会调用(function () { "use strict"; angular.module('the-app', ["translator-app"]) .config(translatorConfigurator) .controller(AppController) function translatorConfigurator (translatorProvider) { function theParamsFn (someService) { //use someService to generate and return params object } theParamsFn.$inject = [ "someService" ]; translatorProvider.setUrl("/url/to/translator"); translatorProvider.setParamsFn(theParamsFn); } function AppController (translator) { translator.translate("the-key").then(function (translated) { //do somethid with 'translated'. }); } translatorConfigurator.$injec = [ "translatorProvider" ]; AppController.$inject = [ "translator" ]; }());

String

我如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

短篇小说:

根据Angular $injector documentation

// inferred (only works if code not minified/obfuscated)
$injector.invoke(function(serviceA){});

// annotated
function explicit(serviceA) {};
explicit.$inject = ['serviceA'];
$injector.invoke(explicit);

// inline
$injector.invoke(['serviceA', function(serviceA){}]);

新型

从前有一个穷人translatorProvider。 Angular是一位伟大的超级英雄,帮助translatorProvider$injector武器为特色。 translatorProvidergetParameters函数中构建了factory函数,并在translate中使用了它。

(function () {

  "use strict";

  angular.module("translator-app", [])
    .provider(translatorProvider);

  function translatorProvider() {

    var 
      url,
      paramsFn;

    //Provider Config Functions
    function setUrl (pUrl) {
      url = pUrl
    };

    function setParamsFn (pParamsFn) {
      paramsFn = pParamsFn;
    };


    function factory ($injector, $http, $q) {

      function getParameters() {

        var 
          promise,
          fn;

        if (paramsFn) {
          fn = $injector.invoke(paramsFn);
          promise = $q.resolve(fn());

        } else {
          promise = $q.resolve()
        }

        return promise;

      }

      //Service Function Pseudo
      function translate(key) {

        if (translateions are cached) {
        //return promis of cached translations

        } else {

          getParameters()
            .then(function (params) {
                return $http({
                  url: url,
                  params: params
                });
            })
            .then(function (response) {

              var extracted = ...; //extract field from response.data

              //put extracted into cache

              return $q.resolve(extractedField)

            });
        }

       } //translate

       //Service Object
       return {
          translate: translate 
       };

    } // factory  

    factory .$inject = [
      "$injector",
      "$http"
      "$q"
    ];


    //Exposed functionality       
    this.setUrl = setUrl;
    this.setParamsFn = setParamsFn;      
    this.$get = factory;
  }

}();

现在translator可以配置如下。

(function () {
  "use strict";

  angular.module('the-app', ["translator-app"])
    .config(translatorConfigurator)
    .controller(AppController)

  function translatorConfigurator (translatorProvider) {

    function theParamsFn (someService) {

      return function () {
        //returns some parameters object
      }

    }

    theParamsFn.$inject = [
      "someService"  
    ];

    translatorProvider.setUrl("/url/to/translator");
    translatorProvider.setParamsFn(theParamsFn);

  }

  function AppController (translator) {
    translator.translate("the-key").then(function (translated) {
      //do somethid with 'translated'.      
    });
  }


  translatorConfigurator.$inject = [
    "translatorProvider"
  ];

  AppController.$inject = [
    "translator"
  ];

}());

在这些变化之后,translatorprovider变得更加强大并且帮助了许多其他模块,并且他们从此过上幸福的生活。