I am facing a situation. I have a CanActivate router guard. Usage of the guards causes an unwanted reload of the whole page.
I implemented two versions of the guard and figured out something I do not understand. Can anybody explain the behavior and suggest a solution? Here is the routing:
const routes: Routes = [{
path: '',
component: DashboardComponent,
children: [{
path: 'overview',
component: OverviewComponent,
},
{
path: 'profile',
canActivate: [TestGuard],
component: ProfileComponent,
},
],
}, ];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class MyRoutingModule {}
Guard Version 1 (works as expected):
import {
Injectable
} from '@angular/core';
import {
ActivatedRouteSnapshot,
CanActivate,
RouterStateSnapshot,
} from '@angular/router';
import {
Observable,
of
} from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class TestGuard implements CanActivate {
constructor() {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable < boolean > {
return of(true);
}
}
Guard Version 2 (reloads the whole page):
import {
Injectable
} from '@angular/core';
import {
ActivatedRouteSnapshot,
CanActivate,
RouterStateSnapshot,
} from '@angular/router';
import {
Observable,
of
} from 'rxjs';
import {
delay,
map
} from 'rxjs/operators';
@Injectable({
providedIn: 'root',
})
export class TestGuard implements CanActivate {
constructor() {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable < boolean > {
return of(true).pipe(
delay(5000),
map(answer => answer)
);
}
}
My problem is I need to call a service (API request). It is simulated by the delay in the second example. But in this case, it causes the reload of the whole page. What I do not see?