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

官网的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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值