我怎么能将服务注入函数?

时间:2016-09-30 08:50:45

标签: angular typescript

var someObject = {
  func: (http: Http)=>{
    // do something
  }
}

---------------------------------------------

// somewhere in an ng2 module
function injectServices(theObject){

  let services = getServices(theObject.func)

  //inject services into theObject
  ....

}

// return services
function getServices(func: Function){
   // get params' type of func
   let paramTypes = ...
   // get services' singleton
   let singletons = ...

   return singletons;
}

Reflect是否提供了这样的方法,以便我可以获得params'功能的类型?我怎么能得到服务类'单?

场景是我将采用一个实现下面接口的对象来呈现表单视图,我有一些自定义服务应该在运行时注入$ validator,$ parser和$ formatter。

interface IViewSchema {
  "title": String,
  "buttons": [
    {
      "buttonText": String,
      "role?": "cancel" | "submit",
      "callback?": 'cancel' | 'submit' | Function,
      "disabled": String
    }
  ],
  "viewTemplate?": String,
  "formControls?": [
    {
      "formTemplate?": String,
      "label": String,
      "maxLength?": number, // max length of input
      "minLength?": number, // min length of input
      "hidden?": String, // if hidden is true, hide the form control
      "disabled?": String, // if data is editable or not, default true,
      "placeholder?": String,
      "model?": String,
      "$validate?":Function[],
      "$parser?": { // parse modal data to view data
        "async?": boolean, // default false, run async parser or not
        "remote?": { // enabled only when async is true
          "url": String, // remote url
          "method?": String, // calling method
          "headers?": JSON, 
          "body?": String | JSON
        },
        "parse?": Function
      },
      "$formatter?": Function
    }
  ]
}

1 个答案:

答案 0 :(得分:0)

我在项目中遇到了同样的问题。我们正在使用Angular 4 + Redux。 以下是我如何解决它:

import { AppActions } from '../app.actions';
import { IAction } from './model.interface';
import { SomeService} from '../services/some.service';
const someService = new SomeService();
export function someReducer(reducersKey) {
   return function (state: IState = INITIAL_STATE,
                    action: IAction): IState {
if (action.type === AppActions.REHYDRATE) {
  if (action.payload) {
const newState = someService.awesomeMethod();
    return {...state, ...newState};
  }
  return state;
 }
 return state;
};