Using a BehaviorSubject to store and share a variable (username) among components has been working well for displaying the username on templates. However, there is a desire to utilize the value of the BehaviorSubject in a service where it can be used as a parameter for a method like myMethod(username) { do stuff }.
The issue appears to be that the value of the BehaviorSubject isn't readily available when the method is called. Attempts have been made to call the method in both the constructor and ngOnInit lifecycle hook, but logging it to the console reveals that initially, it is undefined and only later does it log with the correct username value. Is it feasible to use a BehaviorSubject to retrieve a value passed as an argument to a method?
In this scenario, there is an auth.service containing the BehaviorSubject (with login/auth details omitted as they are not pertinent here). This BehaviorSubject is then subscribed to in newform.component.ts. While the value can be displayed on the newform template, the aim is to subscribe to the BehaviorSubject's value in the newform component and pass it to a method that invokes a service returning an array of locations based on the username. The goal is to populate an input on the newform template with these locations before the user begins filling out the form.
Below is some code:
auth.service.ts
...
newform.component.ts
...
locationslist.service.ts
...
While the locationslist service functions appropriately if the "accountname" is hardcoded into the getUserLocations(accountname) argument, using the BehaviorSubject value results in an initial 500 HTTP response error in the console followed by successful location retrieval. It appears that the BehaviorSubject variable is delayed in appearing. Is there a way to effectively pass the BehaviorSubject value as an argument to a method, or perhaps a better approach to achieve the desired outcome?