我想在我的 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
是我的 Angular 2 http 包装器,用于一些自定义 http header 、正文等。
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), <
最佳答案
您传递了错误的上下文。
The expression for the method decorator will be called as a function at runtime, with the following three arguments:
1) 静态成员的类的构造函数,或实例成员的类的原型(prototype)。
2) ..
因此,在您的情况下,target
是 TemplatesService.prototype
,但您应该使用当前实例调用方法。
尝试以下操作
descriptor.value = function(...args:any[]) { // don't forget function
let ret = method.apply(this, args); // pass current context
关于angular - 如何在 Angular 注入(inject)服务中使用自定义装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45430011/