Home > Software design >  DI, constructor, and field initialization execution order
DI, constructor, and field initialization execution order

Time:06-11

I have the following example code in Angular:

@Injectable({
    providedIn: 'root',
})
export class MyService {

    constructor(private dependentService: DependentService) {} // this is called second
    public myField$ = this.init() // this is called first

    init(){
        return this.dependentService.getAnObservable()
    }
}

When MyService is instantiated:

  • myField$ gets initialized first before constructor is called. I can verify that by using e.g console.log

  • However, myField$ initialization relies on dependentService, which is injected via, again, the constructor

So how is that possible without any error?

CodePudding user response:

You should take a look at how your example compiles to javascript - I've imported it into playground for you here.

As you can see, first the fields from the constructor parameters are assigned, then the fields from outside of constructor are initialized, and only then the constructor body is executed.

  • Related