angular - Angular 组件和 ngOnInit 的自定义装饰器
问题描述
我正在尝试创建一个自定义装饰器来修补ngOnInit
Angular 组件上的函数。我的装饰器被调用,我可以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' );
}
}
解决方案
我处理这个问题已经有一段时间了。就我而言,我使用的是 Ivy,我必须在 tsConfig.json 中将其关闭。只需将 enableIvy 设置为 false 并重新启动您的应用程序,它应该可以工作。
你也可以在 GitHub 上关注这个问题
推荐阅读
- flask - 如何在为渲染提供数据期间动态加载 ModelView 中的 form_extra_fields 之一的选择?
- html - 增加/减少浏览器缩放时具有不同高度的“显示表格单元格”
- sql - SQL - 当存在具有“name”列的类似表时,调用列“name”或“client_name”更好吗?
- c# - 为什么发送数据到服务器时会出现问号?
- typescript - 将方法参数声明为与附加属性的接口
- c# - 如何将 SetAlphamaps 设置为一个特定的纹理?
- php - 为什么curl在php中做成函数时不起作用
- xcode - iOS 13 - 以编程方式以全屏模式将新故事板 nv/vc 转为模态
- python-3.x - 使用分页抓取所有 href 链接
- scala - 使用 Spark 将 yyyyMMdd 转换为日期