Lazy loading with DI into base class

Situation:

I have a base class Base. Main extends Base. Main passes a service in to Base via super(). Base then calls a method on that service.

Problem:

The service is undefined in Base. Unless I console.log(_service) prior in the base class. I suspect a race condition related to lazy loading via AsyncRoute, or maybe its an instantiation issue… either way, I’m not sure how to even start correcting it.

Main.ts:

export class Main extends Base {
    constructor(private _service:SomeService) {
        super(this._service);
    }
}

Base.ts:

@Injectable()
export class Base {
    constructor(_service) {
        _service.doSomething(true);
    }
}

The code blows up at _service.doSomething(true) with error:

EXCEPTION: Error during instantiation of Main!

ORIGINAL EXCEPTION: TypeError: Cannot read property ‘doSomething’ of undefined

But if I try to trace why _service is undefined doing the following – magically it works???

Base.ts:

@Injectable()
export class Base {
    constructor(_service) {
        console.log("_service?", _service); // if this is here...
        _service.doSomething(true);  // ...then the error no longer occurs here
    }
}

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

You may use interface for the service to resolve this issue as follows.

interface IService{
   doSomething();
}

Now modify the base class as follows.

export class Base {
constructor(_service: IService) {
    _service.doSomething(true); 
  }
}

Note: The SomeService should implements IService
Hope this will resolve your issue.

Jason
Guest

The problem was that I was using a static service, so I should have been doing SomeService.doSomething() instead of trying to instantiate it like _service:SomeService.

That’s why the console.log “fixed” it – it was being instantiated within the console.log() statement, and then existed in time for the actual usage of it.