Angular service injecting another service (both children of same abstract class) can’t access injected service’s methods ("reading undefined")

Published

I have multiple services handling notably API requests for different resources. As they’re very similar, I created a parent abstract generic class like this:

abstract class GenericService<T>{
    foo(){
        bar();
    }
    abstract bar();
}

But they’re also highly interconnected so I have a lot of them injected into others:

class R1Service extends GenericService<R1>{
    ...
    bar(){/*do something*/};
}

class R2Service extends GenericService<R2>{
    constructor(private r1: R1Service){}
    ...
    bar(){
        this.r1.foo(); //ERROR
    }
}

I’m getting

TypeError: Cannot read properties of undefined (reading 'foo')

It seems that this.r1 is undefined is some contexts, but I fail to see a logic. I have logged the injected services in the constructor and I see them correctly, and then when a third (unrelated) service calls R2Service.foo(), that calls R2Service.bar(), which in turn calls R1Service.foo() where the issue happens, and logs show r1 as undefined even though it wasn’t in the preceding log.

Source: Angular Questions

Answers

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq