angular - 如何在 Angular 注入(inject)服务中使用自定义装饰器

标签 angular decorator

我想在我的 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), <

最佳答案

您传递了错误的上下文。

根据documentation

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

1) 静态成员的类的构造函数,或实例成员的类的原型(prototype)。

2) ..

因此,在您的情况下,targetTemplatesService.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/

相关文章:

javascript - Angular 应用程序无法运行并显示无效配置错误

module - 如何从特定模块创建所有装饰函数的向量?

angular - 处理来自 Angular 2 的身份验证重定向

java - java中装饰器和状态模式的结合——关于OO设计的问题

装饰器模式,Head First 设计模式

python - 修改请求路径的 View 的自定义函数装饰器

python - 使用装饰器将所有 Unicode 字符串转换为二进制字符串是一种好习惯吗?

angular - RxJs 可观察 : How to intercept a cold observable?

javascript - 如何在搜索功能中处理 'No Results Found'

javascript - 更改 ngFor 列表更改的特定元素