When you log in you should be redirected to the dashboard page. When we navigate to the dashboard we are going to do a resolve so that the data is already loaded even before we can see the page. When we go directlry to the link of the dashboard I am not experiencing any problems. The data is retrieved and is shown on the page. When we navigate from the login page to dashboard page, angular goes back to the login page without giving an error message in the console. The logic of retrieving data is isolated in a service class and used in the components as needed.
Routing class
(When you are on the /login page and you want to navigate to /dashboard/templates angular will just stay on /login. When you go directly to /dashboard/templates the data will be loaded immediately)
const routes: Routes = [
{
path: 'login',
component: AuthComponent,
},
{
path: 'dashboard',
component: DashboardComponent,
children: [
{ path: 'home', component: HomeComponent },
{
path: 'templates',
component: TemplatesComponent,
resolve: { templates: TemplateResolver },
},
{ path: '**', redirectTo: 'home' },
],
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class DashboardRoutingModule {}
Service class
@Injectable({
providedIn: 'root',
})
export class TemplateService {
defaultUrl: string = [API URL];
constructor(private http: HttpClient) {}
getTemplates(): Observable<FullTemplateModel[]> {
console.log('getTemplates');
return this.http.get<FullTemplateModel[]>(this.defaultUrl);
}
}
Resolve class
@Injectable({
providedIn: 'root',
})
export class TemplateResolver implements Resolve<FullTemplateModel[]> {
constructor(private templateService: TemplateService) {}
resolve(): Observable<FullTemplateModel[]> {
console.log('resolving');
return this.templateService.getTemplates()
}
}