使用元数据扩展 Angular 5 组件 [英] Extending an Angular 5 component using metadata

查看:23
本文介绍了使用元数据扩展 Angular 5 组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的项目使用 Angular 2 和 Angular 4 时,我能够使用这个有用的装饰器让一个组件扩展另一个组件:

When my project was using Angular 2 and Angular 4, I was able to use this useful decorator for making a component extend another component:

// Modified from https://medium.com/@ttemplier/angular2-decorators-and-class-inheritance-905921dbd1b7#.s9pf0649f
// by Thierry Templier.

import { Component } from '@angular/core';

export function ComponentExtender(annotation: any): ((target: Function) => void) {
  return function(target: Function): void {
    let parentTarget = Object.getPrototypeOf(target.prototype).constructor;
    let parentAnnotations = Reflect.getMetadata('annotations', parentTarget); // TODO: Doesn't work in Angular 5, returns undefined.
    let parentAnnotation = parentAnnotations[0];

    Object.keys(parentAnnotation).forEach(key => {
      if (parentAnnotation[key]) {
        if (!annotation[key]) {
          annotation[key] = parentAnnotation[key];
        }
      }
    });

    let metadata = new Component(annotation);

    Reflect.defineMetadata('annotations', [ metadata ], target);
  };
}

有了这个,你可以创建一个扩展另一个组件类的组件类,使用@ComponentExtender而不是@Component,并从超类继承一些东西,比如模板和样式,如果这些东西不需要在子类组件中改变的话.

With this you could create a component class that extended an another component class, using @ComponentExtender instead of @Component, and inherit things from the superclass like the template and style if those things did not need to be changes in the subclass component.

由于我已将项目移至 Angular 5,这不再有效.注释元数据未定义.

This no longer works now that I've moved my project to Angular 5. The annotations metadata is undefined.

这可能与 AOT 编译有关吗(即使我没有选择该选项)?谁能想出一种方法来恢复这个装饰器曾经为 Angular 2 和 Angular 4 做的事情?

Does this perhaps have something to do with AOT compilation (even though I haven't selected that option)? Can anyone think of a way to revive what this decorator used to do for Angular 2 and Angular 4?

推荐答案

您可以将组件的注解保存在单独的变量中,并与您的组件一起导出,因此您无需从组件的元数据中检索它.这是一个小例子,希望对你有帮助.

You can save component's annotation in separate variable and export it together with your component, so you don't need to retrieve it from component's metadata. here is small example, hope it would help you.

https://stackblitz.com/edit/angular-bxbpwr?embed=1&file=app/asignAnnotations.ts

这篇关于使用元数据扩展 Angular 5 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆