簡體   English   中英

Angular 4 AOT編譯器不支持mixins

[英]Angular 4 AOT compiler does not support mixins

有時我使用Mixins來注入重復的函數,比如slugUrl()

但它不適用於angular 4編譯器。

export function Mixin(decorators: Function[]) {
  return function (classFn: Function) {
    decorators.forEach(decorator => {
      Object.getOwnPropertyNames(decorator.prototype).forEach(name => {
        classFn.prototype[name] = decorator.prototype[name];
      });
    });
  };
}


@Mixin([BehaviorInjected])
export class FooComponent {

}

如果我編譯此代碼,編譯器拋出:

屬性'ngClassControl'在'FooComponent'類型上不存在。

有任何想法嗎?

編輯:由於有人問,這是使用TS mixins再現問題的另一個例子,這次是在模板級別。

組件:

@Component({
    selector: 'home-page',
    template: '<test [tag]="tag"></test>'
})
export class HomePageComponent extends TaggedComponent(MyComponent) {
    public tag = 'hi there';
}

@Component({
    selector: 'test',
    template: '<div></div>'
})
export class TestComponent extends TaggedComponent(MyComponent) {}

混入:

type Constructor<T> = new(...args: any[]) => T;

export function TaggedComponent<T extends Constructor<{}>>(Base: T) {
     class TaggedBase extends Base {
        @Input() tag: string;
     };

     return TaggedBase;
}

export class MyComponent {
    protected subscriptions: Subscription = new Subscription();
  // ...
}

錯誤:

錯誤中的錯誤:模板解析錯誤:無法綁定到'tag',因為它不是'test'的已知屬性。 ( “] [標簽] =” 標記 “>”)

這里的主要問題是角度編譯器的功能有限。(在文檔中閱讀更多內容)

AOT編譯器使用由MetadataCollector生成的元數據。 它使用typescript對象模型( Node樹)( 這就是AOT只能與 ngfactory 一起使用的原因 )來收集生成ngfactory (在某些情況下也是ngsummary )文件所需的所有信息。

您提供的示例與AOT編譯器完全不同:

1)自定義裝飾

@Mixin([BehaviorInjected])
export class FooComponent {}

MetadataCollector將包括@Mixin裝飾中的元數據FooComponent符號(項目在decorators陣列),但它會被跳過時AOT StaticReflector將調用simplify ,因為Mixin裝飾器未在特殊的地圖注冊僅包括嚴格定義裝飾器( 源代碼

此外,如果我們甚至將它包含在該映射中,它仍然不會在編譯期間執行,因為它僅適用於受支持的裝飾器。

2)調用自定義功能

export class HomePageComponent extends TaggedComponent(MyComponent) {

MetadataCollector 會將 TaggedComponent作為符號添加到元數據集合中,如{__symbolic: 'error', message: 'Symbol reference expected'}; 但它也會在StaticReflector 被跳過

據我所知,目前還沒有解決方案來支持它。

請參閱https://github.com/angular/angular/issues/19145

我相信這是同樣的問題。 對於mixins,裝飾器繼承被破壞,因此目前您必須復制裝飾屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM