Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
angular 2注入在继承中不起作用_Angular_Dependencies - Fatal编程技术网

angular 2注入在继承中不起作用

angular 2注入在继承中不起作用,angular,dependencies,Angular,Dependencies,最近,我们从Angular 2.0升级到了2.4,从那以后,我们在继承方面遇到了问题。 如果我们调用子项,则所有依赖项都将未定义 子级没有构造函数,这意味着它使用父级构造函数 代码如下: @Injectable() export class ChildComponent extends ParentComponent { } export class ParentComponent implements OnInit, AfterViewInit, AfterViewChecked {

最近,我们从Angular 2.0升级到了2.4,从那以后,我们在继承方面遇到了问题。 如果我们调用子项,则所有依赖项都将未定义

  • 子级没有构造函数,这意味着它使用父级构造函数
代码如下:

@Injectable()
export class ChildComponent extends ParentComponent {

}


export class ParentComponent implements OnInit, AfterViewInit, AfterViewChecked {

    constructor(protected _activitySettingsControlService: ActivitySettingsControlService,
                protected _changeDetectionRef: ChangeDetectorRef,
                protected _elemRef: ElementRef,
                protected _apiService: ApiService) {

    }
所有依赖项都是以这种方式取消查找的


原因是什么?

没有完整的例子,我们只能猜测。考虑使用下面作为请求的起点。 显示组件继承和服务注入协同工作的代码示例:

import { Component, Injectable } from '@angular/core';

@Injectable()
export class SomeDependency {
  public foo() {
    return 'bar';
  }
}

@Component({
  selector: 'parent-comp',
  template: `<h1>Hello from ParentComponent {{name}}</h1>`,
  providers: [
    SomeDependency
  ]
})
export class ParentComponent { 
  public name;
  constructor(private dep: SomeDependency) {
    this.name = this.dep.foo();
  }
}

@Component({
  selector: 'child-comp',
  template: `<h1>Hello from ChildComponent. SomeDependency returned {{name}}</h1>`,
  providers: [
    SomeDependency
  ]
})
export class ChildComponent extends ParentComponent { 

}


@Component({
  selector: 'my-app',
  template: `<child-comp></child-comp>`
})
export class AppComponent { 

}
从'@angular/core'导入{Component,Injectable};
@可注射()
导出类依赖项{
公共食物({
返回“bar”;
}
}
@组成部分({
选择器:'父组件',
模板:`Hello from ParentComponent{{name}}`,
供应商:[
某种依赖
]
})
导出类ParentComponent{
公共名称;
构造函数(私有dep:SomeDependency){
this.name=this.dep.foo();
}
}
@组成部分({
选择器:'子组件',
模板:`Hello from ChildComponent.SomeDependency返回{{name}}`,
供应商:[
某种依赖
]
})
导出类ChildComponent扩展了ParentComponent{
}
@组成部分({
选择器:“我的应用程序”,
模板:``
})
导出类AppComponent{
}
有关工作示例,请参见此plunker:

我(也)不熟悉在SO中提供示例,所以我可能错过了一些最佳实践。希望人们会对改进建议发表意见


总的来说,这种组件继承并不是最好的方式——我更喜欢组件的组合而不是继承。继承——如果确实需要的话——可能更适合服务:

为什么这些“组件”都不是实际的
@Component
?请给出一个正确的答案。在child中我们没有@Component。仅在父对象中,示例中没有任何一个。ChildComponent应该是ParentComponent的子级吗?因为它不是。再说一次,对不起,我错了。edited@EliadAyehu考虑使用柱塞创建一个例子。显示服务继承的示例: