我有一个从父类继承的组件,它本身被注入了一个服务。该服务也用于子类(组件(中。我是否必须在父类和子类中导入和注入服务两次?
对我来说,这似乎是代码复制(作为孩子的一只小鸡和蛋必须导入服务才能将其作为参数传递给父母……父母已经导入了它!(。
应用程序组件.ts(子类(
import { Component, OnInit } from '@angular/core';
import { HelperClass } from 'src/app/helper-class';
/**** Duplicate import with the parent class HelperClass ****/
import { MyService } from 'src/app/my-service.service';
@Component({
selector: 'app-my-component',
templateUrl: './app.component.html',
styleUrls: ['./app.component.sass']
})
export class MyComponent extends HelperClass implements OnInit {
/**** Duplicate injection with HelperClass ****/
constructor(private service: MyService) {
super(service);
}
ngOnInit(): void {
this.myService.log('my service called in MyComponent');
this.helper_class_method();
}
}
辅助类.ts(父类(
import { MyService } from 'src/app/my-service.service';
export class HelperClass {
constructor(public myService: MyService) { }
helper_class_method() {
console.log('helper_class method');
}
}
我的服务。服务。ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
log(text: string) { console.log(text); }
}
示例代码可在https://github.com/manu2504/service-heritage-angular/blob/main/src/app/app.component.ts
我将helper/parent类作为一个服务注入到组件中,这样就解决了问题。
组件可以访问助手服务的公共属性,包括助手服务导入的服务,并且不再需要在组件中导入myService。
新代码:
辅助类.ts
import { Injectable } from '@angular/core';
import { MyService } from 'src/app/my-service.service';
@Injectable({
providedIn: 'root'
})
export class HelperClass {
constructor(public myService: MyService) { }
helper_class_method() {
console.log('helper_class method');
}
}
应用程序组件.ts
import { Component, OnInit } from '@angular/core';
import { HelperClass } from 'src/app/helper-class';
@Component({
selector: 'app-my-component',
templateUrl: './app.component.html',
styleUrls: ['./app.component.sass']
})
export class MyComponent implements OnInit {
// Duplicate injection with HelperClass
constructor(
private helper: HelperClass
) { }
ngOnInit(): void {
// No more the need to declare myService locally
this.helper.myService.log('my service called in MyComponent');
this.helper.helper_class_method();
}
}