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

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

2022-06-10 11:15:00 zsy_ one thousand nine hundred and ninety-one

Official website Aliasing a class interface It's difficult to understand , In addition to the following usage scenarios , Whether there are other usage scenarios , Welcome to participate in the message discussion !!!

One of the usage scenarios :

One of the usage scenarios is as follows Reference Chapter 2 article , You can build class As injectable Direct registration such as DI System , Then the child component can access its parent component, grandfather component, etc .

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_ one thousand nine hundred and ninety-one]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101108201234.html