Angular中的依赖注入

时间:2019-01-29 07:33:18

标签: angular

我有2个文件服务(data-parent.service.ts,data-child.service.ts)。两者都具有a()函数名称。 data-child.service.ts扩展了data-child.service.ts。

app-root.component.ts

@Component({
    selector: 'app-root',
    templateUrl: './app-root.component.html',
    styleUrls: ['./app-root.component.scss']
})
export class AppRoot extends DataParent{
    clicka = () => {
        console.log('click a');
        this.a();
   }
}

data-parent.service.ts

@Injectable()
export class DataParent{
    a(): void {
        console.log('a DataParent');
    }
}

data-child.service.ts

@Injectable()
export class DataChild extends DataParent {
   a = () => {
      console.log('a DataChild');
      super.a();
   }
}

当应用程序根组件调用data-child.service.ts的函数名a(),执行data-child.service.ts的函数a()时,如何执行此操作。

结果:“单击a” “ DataChild” “ DataParent”

2 个答案:

答案 0 :(得分:0)

constructor(){}的{​​{1}}中,您可以在Angular中使用依赖注入

app-root component

比您可以同时使用两个功能示例:

    constructor(private dataParentService: DataParentService(or your class name of data-parent.service.ts) , 
                private dataChildService: DataChildService(or your class name of data-child.service.ts)) {}

编辑:尝试一下:

 myfunction(){
  this.dataParentService.a() {
    this.dataChildService.a()
  }
}

EDIT#2:

 myfunction(){
  this.dataChildService.a() {
    this.dataParentService.a()
  }
}

还需要在控制器的ts文件顶部导入服务

答案 1 :(得分:0)

创建一个新实例而不是依赖于依赖项注入将为您完成这项工作,但这不是唯一的方法。我粘贴了以下代码片段,以供您参考,以查看所有可能性。

import { Component, OnInit } from '@angular/core';
import { ChildServiceService } from './child-service.service';
import { ParentServiceService } from './parent-service.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  constructor(private childService: ChildServiceService, private parentService: ParentServiceService) { }
  title = 'app';
  childNewService: any;
  parentNewService: any;
  ngOnInit(){
    this.childNewService = new ChildServiceService();
    this.parentNewService = new ParentServiceService();
    this.childService.callService();
    this.parentService.callService();
    this.childNewService.callService();
    this.parentNewService.callService();
  }

}

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

@Injectable({
  providedIn: 'root'
})
export class ParentServiceService {

  callService(){
    console.log('Inside Parent Service');
  }
}

import { Injectable } from '@angular/core';
import { ParentServiceService } from './parent-service.service';

@Injectable({
  providedIn: 'root'
})
export class ChildServiceService extends ParentServiceService{

   callService(){
     console.log('Inside Child Service');
   }


}