当前位置:网站首页>【Question】what‘s the scenario of aliasing a class interface

【Question】what‘s the scenario of aliasing a class interface

2022-06-10 11:08:00 zsy_1991

官网的Aliasing a class interface 理解起来比较困难,除了以下使用场景,是否还要其他使用场景,欢迎大家参与留言讨论!!!

其中一个使用场景:

其中一个使用场景是如Reference 章节第二篇文章,可以将组建class 作为injectable 直接注册如DI 系统,然后子组件可以访问到他的父组件和祖父组建等。

Aliasing a class interface

Generally, writing variations of the same parent alias provider uses forwardRef as follows.

# dependency-injection-in-action/src/app/parent-finder.component.ts

providers: [{
     provide: Parent, useExisting: forwardRef(() => AlexComponent) }],

To streamline your code, extract that logic into a helper function using the provideParent() helper function.

# dependency-injection-in-action/src/app/parent-finder.component.ts

// Helper method to provide the current component instance in the name of a `parentType`.
export function provideParent
  (component: any) {
    
    return {
     provide: Parent, useExisting: forwardRef(() => component) };
  }

Now you can add a parent provider to your components that’s easier to read and understand.

# dependency-injection-in-action/src/app/parent-finder.component.ts

providers:  [ provideParent(AliceComponent) ]

Aliasing multiple class interfaces

To alias multiple parent types, each with its own class interface token, configure provideParent() to accept more arguments.

Here’s a revised version that defaults to parent but also accepts an optional second parameter for a different parent class interface.

# dependency-injection-in-action/src/app/parent-finder.component.ts

// Helper method to provide the current component instance in the name of a `parentType`.
// The `parentType` defaults to `Parent` when omitting the second parameter.
export function provideParent
  (component: any, parentType?: any) {
    
    return {
     provide: parentType || Parent, useExisting: forwardRef(() => component) };
  }

Next, to use provideParent() with a different parent type, provide a second argument, here DifferentParent.

# dependency-injection-in-action/src/app/parent-finder.component.ts

providers:  [ provideParent(BethComponent, DifferentParent) ]

Reference

原网站

版权声明
本文为[zsy_1991]所创,转载请带上原文链接,感谢
https://blog.csdn.net/zsy_1991/article/details/124927568