1

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?

1
  • Just assign myField$ in the ctor(?) Commented Jun 10, 2022 at 9:56

1 Answer 1

2

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.