arrays - Angular 7:自定义类装饰器破坏组件范围
问题描述
我有一个装饰器,它会ngOnInit
写一个console.log
日志装饰器.ts
export function Log(): ClassDecorator {
// Decorator Factory
return (target: Function) => {
const ngOnInit: Function = target.prototype.ngOnInit;
target.prototype.ngOnInit = ( ...args ) => {
console.log('ngOnInit:', target.name);
if ( ngOnInit ) {
ngOnInit.apply(this, args);
}
};
};
}
和一个HelloComponent
使用@Log()
和导入服务的ngOnInit
你好.component.ts
import { Component, Input, OnInit } from '@angular/core';
import { Log } from './log.decorator';
import { HelloService } from './hello.service';
@Component({
selector: 'hello',
template: `<p>Hello! thanks for help and open the browser console for see the error!</p>`,
styles: [``]
})
// if you remove @Log(), helloService.sayHello() works!
@Log()
export class HelloComponent implements OnInit {
constructor(private helloService: HelloService){}
ngOnInit(){
this.helloService.sayHello();
}
}
但这会导致异常:
错误类型错误:无法读取未定义的属性“sayHello”
@Log()
如果我从中删除HelloComponent
有效!
装饰器似乎破坏了组件范围:
ngOnInit.apply(this, args); // line 13: log.decorator.ts
在此调用之后,this.helloService
is undefined
in the ngOnInit
of HelloComponent
,但没有@Log()
,this.helloService
是一个HelloService
实例。
我该如何解决?
Stackblitz 上的实时示例: https ://stackblitz.com/edit/angular-7hhp5n
解决方案
箭头函数强制上下文this
成为封闭的词法上下文,它是Log
函数的执行上下文。
要拥有组件上下文,您应该使用简单的函数表达式:
target.prototype.ngOnInit = function( ...args ) {
...
}
推荐阅读
- asp.net-web-api - rdlc报告无法解析正则表达式
- html - 工具提示显示在元素下方
- tomcat - tomcat java.lang.NullPointerException
- java - 一个接一个地执行回调
- python - 使用分析对象的错误不可调用
- powerbi - 适用于 SaaS 的 Power BI 网关架构
- java - 无法在我的应用程序的 java 文件夹中创建 Application.java 文件
- mysql - SQL 按组排列的前 3 条最新记录
- dockerfile - 有没有办法解决dockerfile
- ruby-on-rails - Rails 中有类似 Laravel Passport 的东西吗?