piernik
piernik

Reputation: 3657

Injecting service to parent class

Is it possible to inject services into parent class? I've got two classes. One parent class and ex. IncomeService which extends parent.

Parent:

@Injectable()
export class ObjectService {
    constructor(protected apiService: ApiService,
                protected cacheService: CacheService) {
    }
}

IncomeService

@Injectable()
export class IncomeService extends ObjectService {
    test() {
        this.apiService; //is undefined
    }
}

I want to inject servcies to parent since every child will use those services and are used in parent class. As I see angular is not injecting apiService and cacheService to IncomeService. Is it a feature or a bug?

Upvotes: 2

Views: 822

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657308

There is basically no other way than to repeat the constructor parameters in the subclass and pass it to the superclass using the super(...) call.

@Injectable()
export class IncomeService extends ObjectService {
    constructor(protected apiService: ApiService,
                protected cacheService: CacheService) {
      super(apiService, cacheService);
    }
    test() {
        this.apiService; //is undefined
    }
}

There are answers with some ugly hacks to work around this but I'd discourage.

Upvotes: 4

Related Questions