Issue
I have one component that inherits from a parent class, which itself gets injected a service. That service is also used in the child class (the component). Am I obliged to import and inject the service twice, both in the parent and the child class?
It seems like code duplication to me (and a little chicken-and-eggish as the child must import the service to pass it as a parameter to the parent... which already imports it!).
app.component.ts (child class)
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();
}
}
helper-class.ts (parent class)
import { MyService } from 'src/app/my-service.service';
export class HelperClass {
constructor(public myService: MyService) { }
helper_class_method() {
console.log('helper_class method');
}
}
my-service.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
log(text: string) { console.log(text); }
}
Sample code is available at https://github.com/manu2504/service-heritage-angular/blob/main/src/app/app.component.ts
Solution
I made the helper/parent class a service, that I inject in the component, and this solves the problem.
The component can access the public properties of the helper service, including the services imported by the helper service, and there is no more the need to import myService in the component.
New code:
helper-class.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');
}
}
app.component.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();
}
}
Answered By - manuchaud100
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.