Lukas Caniga
Lukas Caniga

Reputation: 399

Angular 4+ send service from child to parent via interface

I was searching for answer several hours.. Is possible in angular to send from child to parent service via interface?

Child extends from Parent

constructor(public locationService: LocationService) {
 super(locationService);  //parent 
}

And parent looks like:

constructor(generalService?: IService) {
    this.myService = generalService;
  }

and than I want to do something like: this.myService.doLogic();

I got runtime error: Error: Uncaught (in promise): Error: Can't resolve all parameters for ParentComponent: (?).

Thanks for any hint or help..

Upvotes: 0

Views: 128

Answers (2)

Krzysztof Raciniewski
Krzysztof Raciniewski

Reputation: 4924

The best way to design component inheritance in Angular framework is passing Injector instance to base component and injecting dependencies in the base component.

Base component class implementation:

export class BaseComponent {
    protected locationService: LocationService;
    constructor(injector: Injector) {
        this.locationService = this.injector.get(LocationService);
    }
}

Child component:

import { Component, Inject, Injector } from "@angular/core"; // Import injector from @angular/core

@Component({
    selector: "child-component",
    templateUrl: "child-component-template.html",
    styleUrls: [
        "./child-component-styles.scss"
    ]
})
export class ChildComponent extends BaseComponent{
    constructor(
        @Inject(Injector) private injector: Injector
    ) {
        // Pass injector instance to base class implementation
        super(injector);
    }
}

Now in the child component you can use LocationService by calling this.locationService.doSomethind();

Upvotes: 1

Ravi Sevta
Ravi Sevta

Reputation: 3085

You should not have to extend Component, By extending component it brings only class property. So change parent from Component to simple class.

interface IService {
  doLogic();
}

@Injectable()
export class LocationService implements IService {
  doLogic() {
    console.log('service goes here...');
  }
}

export class ParentComponent {
  constructor(public locationService?: IService) {
  }
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent extends ParentComponent {
  constructor(locationService: LocationService) {
    super(locationService);

    this.locationService!.doLogic();
   }
}

Upvotes: 0

Related Questions