我使用自定义装饰器来动态地在hook [ngAfterViewInit]添加procces。如果组件中不存在此钩子,我会修改原型以添加它。
export function MyHook(names: string[]) {
return (target: any) => {
const originalNgAfterViewInit: Function = target.prototype.ngAfterViewInit;
target.prototype.ngAfterViewInit = () => {
console.log("Do this before");
if (originalNgAfterViewInit) {
originalNgAfterViewInit.call(target);
}
}
return target;
};}
它在JIT模式下工作,但在AOT模式下,我必须在组件中定义一个方法ngAfterViewInit,以便此代码可以工作。
1. 此代码适用于AOT模式和JIT模式:
@Component({
moduleId: module.id,
selector: "my-comp",
templateUrl: "my.component.html"
})
@MyHook(["test"])
export class MyComponent {
public ngAfterViewInit() {
console.log("Hello");
}
}
输出:
在
之前执行此操作您好
2. 此代码仅适用于JIT模式。在AOT模式下不起作用:
@Component({
moduleId: module.id,
selector: "my-comp",
templateUrl: "my.component.html"
})
@MyHook(["test"])
export class MyComponent {
}
没有输出。但我们期望:“在此之前做到这一点”
为什么呢?以及如何解决这个问题?
我使用Angular 2.4