typescript - 用于 Angular 组件和 ngOnInit 的自定义装饰器
我正在尝试创建一个自定义装饰器,以便在 Angular 组件的 ngOnInit 函数中进行补丁。我的装饰器会被调用,并且我能够从原型中获取 ngOnInit,但是我的替换函数在组件生命周期中从未被调用。有人知道为什么我的代码不起作用吗?
import {Component, OnInit} from '@angular/core';
function TestDecorator( theClass: Function ) {
console.log( 'decorator called' );
const ngOnInit = theClass.prototype.ngOnInit;
theClass.prototype.ngOnInit = function() {
console.log( 'decorator nginit' );
ngOnInit();
};
}
@TestDecorator
@Component( {
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
} )
export class AppComponent implements OnInit {
title = 'angtest';
constructor() {
console.log( 'component constructed' );
}
ngOnInit(): void {
console.log( 'component nginit' );
}
}
答案#1
我已经处理这个问题有一段时间了。在我的情况下,我使用的是 Ivy,我不得不在 tsConfig.json 中将其关闭。只需将 enableIvy 设置为 false 然后重启你的应用程序,它应该就能工作。
你也可以在 GitHub 上关注此问题