首页 > 解决方案 > Angular 组件和 ngOnInit 的自定义装饰器

问题描述

我正在尝试创建一个自定义装饰器来修补ngOnInitAngular 组件上的函数。我的装饰器被调用,我可以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' );
   }
}

标签: angulartypescript

解决方案


我处理这个问题已经有一段时间了。就我而言,我使用的是 Ivy,我必须在 tsConfig.json 中将其关闭。只需将 enableIvy 设置为 false 并重新启动您的应用程序,它应该可以工作。

你也可以在 GitHub 上关注这个问题


推荐阅读