I have [AuthGuard] for /profile/personal-data which watching if the user has logged or not . And after login() I do this.router.navigates['profile/persnal-data'] and it works correct. But when I'm not logged in and try to put in browser /profile/person then app redirects me to ?path=%2Fprofile%2Fpersonal-data. I don't know what am I doing wrong ?
route.config
const routes: Routes = [
{
path: '',
component: ProfileComponent,
children: [
{ path: '', redirectTo: 'personal-data', pathMatch: 'full' },
{ path: 'personal-data', component: PersonalDataComponent, canActivate: [AuthGuard] },
]
}
];
Gurard.ts
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthentificationService } from '../services/authentification.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private authentificationService: AuthentificationService,
) { }
isEmpty(obj): boolean {
for (const prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
return JSON.stringify(obj) === JSON.stringify({});
}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return Observable.create(observer => {
if (
localStorage.getItem('access-token-1cb-portal') != null &&
localStorage.getItem('expires-at-access-1cb-portal') != null &&
localStorage.getItem('refresh-token-1cb-portal') != null &&
localStorage.getItem('expires-at-refresh-1cb-portal') != null
) {
observer.next(true);
observer.complete();
return;
} else {
this.router.navigate(['/'], {
queryParams: {
path: state.url
}
});
observer.next(false);
observer.complete();
return;
}
});
}
}
UPD 1
I have updated my Guard to simple
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request);
}
It still redirect's me to main page with strange url http://localhost:4200/?path=%2Fprofile%2Fpersonal-data but when I remove canActivate: [AuthGuard] from my route.config for profile route ,and it workes and redirect to the right page. What is going wrong , why the guard make huge sense for this behaviour ?
this.router.navigates['/profile','persnal-data']path=%2Fprofile%2Fpersonal-data