I have a service that makes request to an api and according to its response I should decide that a component must be loaded or not. but because of a time spent to receive the response, component loads regardless of response status, and after some time (about 0.5 secs) response is received and if the component must not be loaded, we navigate to somewhere else. I don't want the component to be loaded before receiving the response.
I'm using canActivate function from AuthGuard in angular 4 as below:
export class AuthGuard implements CanActivate {
access = true;
res: any;
constructor(private router: Router, private routeService: RouteService){}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
setTimeout(() => {
if( !this.exept.includes(this.router.url) ){
this.routeService.FormOperation(this.router.url).subscribe(item=> {
this.res = item;
if (this.res.status == 200) {
if (this.res.data.Access[1] == false) {
this.access = false;
}
if (this.access == true)
{
return true;
}
else {
this.router.navigate(['/dashboard']);
return false;
}
})
}
},0);
if (sessionStorage.getItem('token') && this.access)
{
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}
I'm using setTimeout so that I can get a correct this.router.url .
Update:
I added resolver as below:
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): void {
this.routeService.FormOperation(this.router.url).toPromise()
.then(response => {
this.form_operation_data = response;
if(!this.form_operation_data['data']['Access'][1]) {
this.router.navigate(['/dashboard']);
}
})
.catch(err => {
console.error(err);
});
}
but still the component loads before response data receives ...