Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject dependency service to parent class in angular

I have class parent and child. The child class extends parent. I need to @Inject injectable class service to parent because all child's using it. How I can do it?

like image 374
Michał Wojas Avatar asked Dec 05 '22 12:12

Michał Wojas


2 Answers

You can inject any service or class from parent with Injector class, you need to inject the Injector class from child and pass it to the parent by super(injector) so parent can inject your reusable services from the injector coming from child.

Parent class :

export class BaseComponent implements OnInit {

    protected myService: MyService

    constructor(injector: Injector) {
        this.myService = injector.get(MyService)
    }

    ngOnInit() {
        console.log('ngOnInit from Base');
    }
}

Child class :

export class AppComponent extends BaseComponent {

  constructor(injector: Injector) {
    super(injector)
  }

  ngOnInit() {
    super.ngOnInit()
    this.myService.getUsers()
  }
}

Using this way you do not want to inject each services from child to pass one by one to parent, the above way is more efficient to inject from parent.

like image 57
Googlian Avatar answered Dec 09 '22 13:12

Googlian


You can't inject a dependency into a parent class because Angular does not instantiate it for you. It creates an instance of your child class, which effectively initialises the parent class too (this isn't terribly accurate, as classes are just syntactic sugar, but it's suitable for this discussion).

One common solution is to just set up the child classes to be injectable and then pass the dependencies up using super. e.g.:

class Parent {
    constructor(protected someService: SomeService) { }
}

@Injectable()
class Child extends Parent {
    constructor(someService: SomeService) {
        super(someService);
    }
}

If Parent doesn't actually need the dependency itself, you're better off just using @Injectable() on your child classes, which could have their own private reference to the dependency.

like image 45
Kirk Larkin Avatar answered Dec 09 '22 14:12

Kirk Larkin