【问题标题】:Angular 4+ send service from child to parent via interfaceAngular 4+通过接口将服务从孩子发送到父母
【发布时间】:2018-12-27 07:27:52
【问题描述】:

我一直在寻找答案几个小时.. 是否可以通过接口从子服务发送到父服务?

  • 父组件
  • 子组件(扩展父组件)
  • 服务接口
  • 服务(例如 locationService)(实现上面的 iface)

子从父继承

constructor(public locationService: LocationService) {
 super(locationService);  //parent 
}

父母看起来像:

constructor(generalService?: IService) {
    this.myService = generalService;
  }

比我想做的事情:this.myService.doLogic();

我收到运行时错误:错误:未捕获(承诺中):错误:无法解析 ParentComponent 的所有参数:(?)。

感谢任何提示或帮助..

【问题讨论】:

  • 你是在扩展组件还是服务?
  • 子组件扩展父组件,定位服务实现IService接口
  • 是否还有扩展父组件的子组件?
  • 您的LocationService 类是否实现IService 接口?否则,子调用super(locationService)的参数与父构造函数参数不匹配,即期望接口IService
  • 您必须将父级从Component 更改为简单类。有关更多详细信息,请查看我的答案

标签: javascript angular typescript interface


【解决方案1】:

在 Angular 框架中设计组件继承的最佳方法是将 Injector 实例传递给基础组件并在基础组件中注入依赖项。

基础组件类实现:

export class BaseComponent {
    protected locationService: LocationService;
    constructor(injector: Injector) {
        this.locationService = this.injector.get(LocationService);
    }
}

子组件:

import { Component, Inject, Injector } from "@angular/core"; // Import injector from @angular/core

@Component({
    selector: "child-component",
    templateUrl: "child-component-template.html",
    styleUrls: [
        "./child-component-styles.scss"
    ]
})
export class ChildComponent extends BaseComponent{
    constructor(
        @Inject(Injector) private injector: Injector
    ) {
        // Pass injector instance to base class implementation
        super(injector);
    }
}

现在在子组件中你可以通过调用this.locationService.doSomethind()来使用LocationService;

【讨论】:

    【解决方案2】:

    你不应该扩展Component,通过扩展组件它只带来类属性。所以将父类从Component 更改为简单类。

    interface IService {
      doLogic();
    }
    
    @Injectable()
    export class LocationService implements IService {
      doLogic() {
        console.log('service goes here...');
      }
    }
    
    export class ParentComponent {
      constructor(public locationService?: IService) {
      }
    }
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent extends ParentComponent {
      constructor(locationService: LocationService) {
        super(locationService);
    
        this.locationService!.doLogic();
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-07-31
      • 2021-06-04
      • 2022-08-03
      • 2017-07-01
      • 2022-11-15
      • 2015-09-14
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      相关资源
      最近更新 更多