I'm facing an issue in my Angular app where I have to validate the tenantId and fetch relevant data when the page is reloaded. Currently, I have scattered this logic across multiple components in my code. However, I want to streamline this process to avoid repetition. How can I create a centralized solution that can be easily accessed from any component?
Here's how I've implemented it:
// Code snippet for checking route on page reload
this.route.paramMap
.pipe(
takeUntil(this._unsubscribeAll),
switchMap((params: Params) => {
const tenantId = params.get('tenantId');
if (tenantId) {
return this._apiService.getTenants();
} else {
return of(null); // No tenantId present, return an observable to prevent unnecessary subscriptions
}
}),
filter(tenants => tenants !== null),
take(1) // only need to take one tenant
).subscribe(
(tenants: Tenant[]) => {
const tenantId = this.route.snapshot.paramMap.get('tenantId');
const activeRouteTenant = tenants.find(
tenant => tenant.name === tenantId
);
if (activeRouteTenant) {
this._tenantService.updateTenant(activeRouteTenant);
}
// Ensure components are checked for changes
this._changeDetectorRef.markForCheck();
this.initialDashboardInformation()
}
)
Could you please provide guidance on this matter? Thank you so much :D