2016-09-30 8 views
0
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

号角度DIは唯一のクラスのコンストラクタに注入します。 –

+0

それから、Reflectを通して関数のparam型を得ることができる方法はありますか? –

+0

申し訳ありませんが、私はそれについて知らないです。なぜあなたはそれをクラスにしてAngular2に仕事をさせないのですか? –

答えて

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; 
}; 
関連する問題