Seeking a solution in the given code, I must wait for server calls to initialize cached objects as properties on the class. After researching, I found inquiries on waiting for multiple subscriptions, and decided to utilize forkJoin
as demonstrated. However, this leads to a new dilemma - now I must wait on forkJoin
. How can I achieve this without rewriting the project, which is not asynchronous?
// Question 2
In theory, I could privatize the constructor and implement a static factory method. However, I foresee encountering the same issue of awaiting the async factory method without a mechanism in place. If I opt for this approach, how can I instruct the Angular DI mechanism to a) await the factory method and b) inject the instance (providedIn
'root' exclusively denotes creating a singleton, not instantiating 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
//---
}
}
Working with rxjs 6.5.4 / angular 9.1