после того, как я попробовал любое другое решение, я все еще застрял со своей проблемой, которая заключается в следующем: попытка перейти к другому компоненту, URL-адрес изменился, но я остаюсь на той же странице, целевой компонент не загружен.
Объяснение:
Когда пользователь заходит в приложение, в зависимости от хранилища сеанса он переходит к компоненту HOME или компоненту LOGIN.
Если он попадет на компонент ГЛАВНАЯ, ВСЕ работает, он сможет перемещаться по всему приложению.
в противном случае, если он приземлится на LOGIN, затем войдет в систему, а затем перенаправит на компонент HOME, только тогда больше не будет работать навигация, изменится только URL.
Я использовал отложенную загрузку и authGuard.
Нет ошибки на консоли.
Журнал трассировки маршрутизатора между двумя приведенными выше случаями идентичен (я имею в виду, что во втором случае компонент NavigationEnd является правильным компонентом назначения, но он никогда не загружается)
Вот мой app-routing.module.ts
:
const routes: Routes = [
{
path: '',
redirectTo: 'login',
pathMatch: 'full',
},
{
path: 'home',
loadChildren: './pages/home/home.module#HomeModule',
canActivate: [AuthGuard]
},
{
path: 'description',
loadChildren: './pages/description/description.module#DescriptionModule',
canActivate: [AuthGuard]
},
{
path: 'nsp',
loadChildren: './pages/nsp/nsp.module#NspModule',
canActivate: [AuthGuard]
},
{
path: 'login',
loadChildren: './pages/login/login.module#LoginModule'
},
{
path: 'mappings',
loadChildren: './pages/mappings/mappings.module#MappingsModule',
canActivate: [AuthGuard]
},
{
path: 'performances',
loadChildren: './pages/performances/performances.module#PerformancesModule',
canActivate: [AuthGuard]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes, {enableTracing: true })],
exports: [RouterModule]
})
export class AppRoutingModule { }
Вот мой auth-guard.service.ts
:
export class AuthGuardService implements CanActivate {
constructor(private storageFactory: StorageFactoryService,
public auth: AuthentificationService,
public router: Router) {}
session_date_expire_on: string;
canActivate(_route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.storageFactory.get('ssid_expires_on') != null) {
var date_stored =
new Date(this.storageFactory.get('ssid_expires_on').value);
}
var current_date = new Date();
if (typeof this.storageFactory.get('userid') !== 'undefined' &&
this.storageFactory.get('userid') !== null &&
date_stored > current_date) {
this.storageFactory.remove('ssid_expires_on');
this.session_date_expire_on = new Date(current_date.getTime() +
environment.inactivity_timeout).toString();
this.storageFactory.set('ssid_expires_on', this.session_date_expire_on);
current_date = null;
return true;
}
localStorage.clear();
sessionStorage.clear();
this.router.navigate(['/login']);
return false;
}
}
мой app.component.ts
перенаправляет непосредственно на компонент HOME, поэтому вызывается authGuard и при необходимости перенаправляется на LOGIN:
export class AppComponent implements OnInit {
constructor(private checkSessionService: CheckSessionService,
private storageFactory: StorageFactoryService,
private ElementRef: ElementRef,
private api_user: AuthentificationService,
private router: Router) { }
ngOnInit() {
console.log("--------- App Component ---------");
this.router.navigate(['/home']);
}
}
Проблема в том, что когда я перехожу к login.component.ts
и нажимаю на функцию журнала, если пользователь аутентифицирован, он переходит на ДОМОЙ, а затем не работает навигация:
export class LoginComponent implements OnInit {
user: UserInfo;
current_date = new Date();
session_date_expire_on: string;
access_granted: boolean;
constructor(private ngZone: NgZone,
private storageFactory: StorageFactoryService,
private api_user: AuthentificationService,
private router: Router,
private route: ActivatedRoute) { }
ngOnInit() {}
log() {
return this.api_user.getUser().subscribe(response => {
if (response.status == 200) {
this.user = response.body;
this.session_date_expire_on = new Date(this.current_date.getTime() +
environment.inactivity_timeout).toString();
this.storageFactory.set('userid', this.user.userId);
this.storageFactory.set('usercountry', this.user.entityCountryName);
this.storageFactory.set('userrights', this.user.profile[0]);
this.storageFactory.set('ssid', uuid());
this.storageFactory.set('ssid_expires_on', this.session_date_expire_on);
this.router.navigate(['/home']);
} else {
this.router.navigate(['/login']);
}
})
}
}
У тебя есть идеи ?
Я уже пробовал ..
--> this.router.navigate([../home])