我之前曾问过我奇怪的路由问题。
我现在有一个解决方案,但仍然偶尔会有奇怪的行为。
我的页面应该转到“登录”,一旦成功,然后转到“主”。这实际上现在有效,除了转到登录->主页->空白('')->主页。最后的“闪烁”或刷新我不明白。这解释了最初的行为,它总是默认为“登录”页面,几乎不会停留在主页上。
它碰巧不“闪烁”(空白并重新加载/刷新)。此时控制台清空。
现在它可以工作了,但我仍然觉得有点奇怪。
截至目前:
- 页面打开
- 空转到主
- 在“main”上,它将查看 SiginGuard,它将路由到“signin”
- 登录页面打开
- 用户输入凭据
- 主页打开
--- 以下是奇怪的事情:
- 它会变空,重定向到,
- 然后通过重定向再次打开主程序
我到处都有警报()来跟踪它 - 没有发生意外的情况
最后注意:如果登录时间超过4~5秒,将重置到登录页面。再次登录时,它将转到主页而不是闪烁(因为它已经“这样做”了)。
有时 API 可能会很慢。我的超时没有任何影响,我的 http 中的某些内容没有等待足够长的时间。
全部代码:
路由:
export const appRoutes: Routes = [
{
path: 'signin',
component: SigninComponent,
data: {
title: 'Login',
subtitle: ''
}
},
{
path: 'main',
component: MainComponent,
canActivate: [SigninGuard],
data: {
title: 'Main page',
subtitle: ''
}
},
{
path: '',
redirectTo: '/main', /// this used to be /signin - which would just should the signin page forever
pathMatch: 'full'
},
{
path: '**',
component: NotFoundComponent,
data: { title: '404' }
}
];
登录卫士:
canActivate() {
const currentUser = this.loginInfo.getUserName();
if (!currentUser) {
// alert("message for me"); // used to have such alerts to track the code - it did never go here
this.router.navigate(['/signin']);
}
// another alert here
return true;
}
登录组件:
signIn(name, pass) {
console.log("****** initiated");
const credentials: IAccount = { UserName: name, UserPassword: pass };
this.loginService.login(credentials).subscribe(result =>
{
console.log("****** response 1");
// alert("response 1");
const response = this.getDecodedAccessToken(result.Token.TokenString);
if(response==null)
{
this.loginResult = response.Status;
alert(this.loginResult); // better error handling needed
this.router.navigate([ prefix + '/signin']);
} else {
if (response.signum.toLowerCase() === credentials.UserName.toLowerCase()) {
// alert("login ok");
this.loginInfo.setUserName(response.name);
this.loginInfo.setUserRole(response.role);
this.loginInfo.setUserId(response.id);
this.router.navigate([ prefix + '/home']); // goes here - then "flashes"
}
}
},
error => { this.errorMessage = <any>error; alert("err " + this.errorMessage); }
);
console.log("the end");
}
和登录服务:
return this.http.post<IResponse>(this.url, JSON.stringify(model), { headers: this.headers }).pipe(
// map(sdd => { return sdd; } ) // used to have an alert to check result here
timeout(990000000),
// tap(result => { alert("pong"); console.log('Login result: ' + JSON.stringify(result)) } ),
catchError(this.handleError) // this alerts any error - no errors
);
}