【问题标题】:I cannot find how I can access DI properties from a child class我找不到如何从子类访问 DI 属性
【发布时间】:2020-08-24 10:54:00
【问题描述】:

我已经在我的 Angular 应用程序上实现了 this 方法,并且登录/注册正在运行。

现在我希望添加一个函数来在我的客户注册/登录组件初始化时运行 OnInit。

我特别希望使用/注入

  1. 我的服务
  2. ActivatedRoute/ActivatedRouteSnapshot 以访问两个组件上的 url 参数。
  3. 位置策略

进入我的子组件(LoginComponent 和 RegistrationComponent),因为它们都派生自 NbLoginComponent 和 NbRegisterComponent 分别

这是我的 register.component.ts

export class NgxRegisterComponent extends NbRegisterComponent {}

这是我的 NbRegisterComponent

export declare class NbRegisterComponent {

    constructor(
        service: NbAuthService, 
        options: {}, 
        cd: ChangeDetectorRef, 
        router: Router);

    register(): void;

    getConfigValue(key: string): any;

    static ɵfac: ɵngcc0.ɵɵFactoryDef<NbRegisterComponent>;

    static ɵcmp: ɵngcc0.ɵɵComponentDefWithMeta<NbRegisterComponent, "nb-register", never, {}, {}, never>;
}

我无法在 NbRegisterComponent 上使用 Injector,因为构造函数不会接受任何属性,而不是参数。

另外,我尝试在 NbRegisterComponent 中声明受保护的成员并将其添加到构造函数中

protected myService : MyService

然后在子类RegisterComponent 中,我将属性添加到构造函数和Super() 的参数中,但注入的属性都是空的/未定义的。

任何帮助都会大有帮助。

【问题讨论】:

  • 如果你扩展你应该可以访问父方法而无需再次注入它们。静态方法虽然无权访问它
  • 返回一个未定义的对象。这似乎是一个类似的问题,但我不能很好地理解它。 github.com/akveo/nebular/issues/1234

标签: angular dependency-injection ngx-admin nebula


【解决方案1】:

嘿嘿嘿,

在子组件中,我为所有需要的对象/属性添加了提供者列表,例如

@Component({
  //...
  providers: [
    {provide: VisitsService, useClass : VisitsService},
  ]
})

在子组件的构造函数中,我将@Inject() 函数附加为

  constructor(
    @Inject(ActivatedRoute)activateRoute : ActivatedRoute,
    @Inject(VisitsService) protected visitService: VisitsService,    
  ){
    super(
      activateRoute, 
      visitService);
  }

现在一切正常。

哦!请记住,父组件也将这些属性注入其构造函数,并且参数的顺序很重要。

【讨论】:

    猜你喜欢
    • 2019-05-29
    • 1970-01-01
    • 2013-03-24
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-12
    • 2022-12-15
    相关资源
    最近更新 更多