2017-08-01 58 views
1

我想在我的angular2服務中使用'AOP',例如,我想請求我的服務器並獲取數據,我將檢查它的返回代碼,我將顯示消息這個返回代碼,如何在角度注射服務中使用自定義裝飾器

例如: 這裏是我的服務:

@Injectable() 
export class TemplatesService { 

constructor(private http: HttpHelper) { 

} 

@show_message 
public templates(search_params = {}): Observable<Array<Template>> { 
    let params = new URLSearchParams() 
    for (let key in search_params) { 
     params.set(key, search_params[key]) 
    } 
    return this.http.AUTH_HTTP_GET('api/templates.json?per=10000', params).map(data=> this.http.extractData(data).templates) 
} 
} 

HttpHelper是一些自定義HTTP頭,身體等我的角2 HTTP包裝..

的show_message裝飾:

export function show_message(target:any,key:any,descriptor:any){ 
    console.log(target,key ,descriptor) 
    const method = descriptor.value 

    descriptor.value = (...args:any[]) => { 

     let ret = method.apply(target, args); 

     return ret; 
    } 

    console.log(method) 

    return descriptor; 
} 

,這裏是錯誤:

VM40526 TemplateIndexComponent_Host.ngfactory.js:5 
ERROR TypeError: Cannot read property 'AUTH_HTTP_GET' of undefined 
     at Object.TemplatesService.templates (eval at <anonymous> (app.cfb7cea….js:194), <anonymous>:31:25) 
     at TemplatesService.descriptor.value [as templates] (eval at <anonymous> (app.cfb7cea….js:2349), < 

回答

2

你傳遞錯誤的上下文。

按照documentation

The expression for the method decorator will be called as a function at runtime, with the following three arguments:

1)無論是類的一個靜態成員,或之類的一個實例構件原型的構造函數。

2)..

所以target你的情況TemplatesService.prototype但應該調用方法與當前實例。

請嘗試以下

descriptor.value = function(...args:any[]) { // don't forget function 
    let ret = method.apply(this, args); // pass current context 
+0

好!很好的答案,謝謝你! – junk