Jake12342134
Jake12342134

Reputation: 1767

Order of Angular dependency injection construction

Within my Angular app, I have a service user-serial-service that makes a single API call to retrieve a user serial as a string, and then stores this value within a BehaviourSubject

I want to use this serial within the constructor of my app.component, but I'm finding that the API call to retrieve the serial is not completing before the app.component's constructor is firing and therefore the userSerial$ is undefined.

This, I assume, is because the app.component is the first component to be generated by Angular, and therefore is the first component to be constructed, meaning that the service's API call will not finish before the app.component is created.

This has got me wondering how exactly Angular instantiated its dependencies and in what order. If I wanted to force the service to be constructed first in order to allow its API call to finish before app.component is instantiated, would this be possible? Is App.Component constructed first and then all of its listed dependencies are constructed after?

export class AppComponent {

    constructor(private _userSerialService: UserSerialService) {
        console.log("User serial: ", this._userSerialService.userSerial$.getValue()); //userSerial$ is undefined
    }
}

export class UserSerialService {

    public userSerial$: BehaviorSubject<string>;

    constructor(private _http: HttpClient) {
      this.getUserSerial().pipe(take(1)).subscribe(res => {
        this.userSerial$ = new BehaviorSubject<string>(res.body.serial)
      })
    }

  }

Upvotes: 0

Views: 1392

Answers (1)

G&#233;r&#244;me Grignon
G&#233;r&#244;me Grignon

Reputation: 4228

In your case you should use APP_INITIALIZER to execute the API call at the boostrap of the application (i won't be able to give you a long answer abouthow to implement it but you might be able to find a lot of tutorials on google).

So when the AppComponent will be initialized, the userSerial will be available. But be careful about the time required to query the API as it might slow down the application intiailization.

More commonly about the class, you can't really act on asynchronous code in the constructor of the lifecycle hook to delay the component creation. The asynchronous code is executed at the class instanciation but it doesn't block the creation waiting for the completion.

So in your case :
* the AppComponent creation start
* the service creation start with an asynchronous execution
* the AppComponent creation ends
* later on the asynchronous code is completed

Upvotes: 1

Related Questions