Do you need to get a value from a service level variable as soon as your application starts up? This would mean that your service would have to initialize, followed by calling the method that populates your service variable, all before your application finishes with the start-up process. Your variable would be undefined because the problem is created by the component reading the value from the service too early, as the service has not yet had a chance to initialize itself and push a value into your variable.
How do we solve this?
I had two solutions for two different use cases.
APP_INITIALIZER let’s your service be initialized when your application starts up instead of when a component calls upon it when needed. We implement the app initializer in our app.module file like so:
With our app initializer now added to the app.module file, we get that service level variable back with a value immediately. No more undefined value 🙂
This solution would work for you if you didn’t need that value to update as you were using your application. I needed this to happen. The value should update in my component every time the variable in my service changed. For this use case I needed to use my second solution, a Behaviour Subject and Observable.
Behavious Subject and Observable
With the behaviour subject and observable I don’t need to initialize my service in time for when the component reads the variable. I can now subscribe to the service level variable, which is now an observable, and push values through the stream using the .next method.
Now the component gets an undefined variable until the service is completely initialized, at which point the service level variable gets updated with a value and the component, that is subscribed to that variable, is updated also.
This was the right solution for my use case as it meant I no longer had to wait for the service to initialize, but it would also update the variable in my component whenever the service variable changed.