In the code below I need to wait on some server calls to initialize objects that are cached as properties on the class.
In researching this issue I found several questions that ask how to wait for multiple subscriptions. The answer I chose was to use forkJoin
as is shown. However I'm only kicking the can down the road. Now I need to wait on forkJoin
. How do I do that? The project I'm working on is not async and I can't go and re-write it.
// Question 2
In theory I could make the constructor private and create a static factory method - however I think I am once again kicking the can as I have no mechanism or place to await the async factory method. If I take this approach how do I tell the Angular DI mechanism to a) await the factory method and b) inject the instance (providedIn
'root' only says create a singleton - does not allow me to actually create the instance).
export class PermissionService {
public initialization : Promise<void>;
private _isAdmin : boolean;
private appPermissionsDict : object;
private dataPermissionsDict : object;
baseUrl = environment.baseUrl + 'permission';
constructor(private http: HttpClient) {
this.initialization = this.init();
}
async init()
{
await forkJoin([
this.getIsAdmin(),
this.getAppPermissions(),
this.getDataPermissions()
]).subscribe(([isAdmin, ap, dp]) => {
this._isAdmin = isAdmin;
this.appPermissionsDict = Object.assign({}, ...ap.map(x => x.id))
this.dataPermissionsDict = Object.assign({}, ...dp.map(x => x.id))
});
//---
// Need to wait here for properties to be set on the class
//---
}
}
Using rxjs 6.5.4 / angular 9.1