代码之家  ›  专栏  ›  技术社区  ›  Alex Lomia

依赖注入在Angular 2+中昂贵吗?

  •  1
  • Alex Lomia  · 技术社区  · 8 年前

    @Directive({
        selector: '[testActiveTab]'
    })
    export class ActiveTabDirective {
    
        @Input('testActiveTab') active: boolean = true;
    
        constructor(
            private parent: TabbedContainerComponent, // <--
            private child: TabComponent               // <--
        ) {
        }
    
        // ...
    
    }
    

    <test-tabbed-container>
        <test-tab>
            <!-- ... -->
        </test-tab>
    
        <test-tab testActiveTab>
            <!-- ... -->
        </test-tab>
    </test-tabbed-container>
    

    正如您可能已经猜到的那样,此指令用于标记选项卡式容器组件内的活动选项卡。

    然而,可能的问题是,每次 ActiveTabDirective parent child 如果有 n 容器中的选项卡, 2 * n .

    依赖注入在Angular2+中是一个昂贵的操作吗?或者它只是传递了一个参考,因此很便宜?

    1 回复  |  直到 8 年前
        1
  •  2
  •   Estus Flask    8 年前

    这里的“昂贵”解决了这个问题 hierarchical dependency injection 在角度上工作,性能影响是结果。

    DI无法实例化和注入未链接到编译元素的组件。

    提供者是单例(在当前注入器的范围内)。如果在当前注入器中未定义提供程序,但在父注入器中将其实例化,则将注入现有的提供程序实例。

    Injectable Directive Component 类都是可注入的,角度明确区分指令/组件(定义见 declarations )来自常规提供商(定义见 providers ),他们的行为不同。指令/组件由编译器实例化,因此不会意外注入其他实例。

    constructor(
        private parent: TabbedContainerComponent,
        private child: TabComponent
    ) {}
    

    ViewChild ContentChild

    推荐文章