【发布时间】:2017-10-23 21:23:47
【问题描述】:
我有一个带有登录方法的 user.service.ts 文件:
login(userName : string, password : string) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http
.post(
this.baseUrl + '/auth/login',
JSON.stringify({ userName, password }),{ headers }
)
.map(res => res.json())
.map(res => {
localStorage.setItem('auth_token', res.auth_token);
this.loggedIn = true;
this._authNavStatusSource.next(true);
return true;
})
.catch(this.handleError);
}
这由我的 login-form.component.ts 上的登录按钮调用:
login({ value, valid }: { value: Credentials, valid: boolean }) {
this.submitted = true;
this.isRequesting = true;
this.errors='';
if (valid) {
this.userService.login(value.email, value.password)
.finally( () =>
this.isRequesting = false
)
.subscribe(
result => {
if (result) {
console.log("calling routing navigate");
this.router.navigate(['/connect']);
console.log(this.userService.isLoggedIn())
console.log("done");
}
},
error => this.errors = error);
}
}
}
当有人使用有效凭据单击登录时,会在本地存储上创建 auth_token,在控制台中我可以看到以下结果:
console.log("calling routing navigate");
this.router.navigate(['/connect']);
console.log(this.userService.isLoggedIn())
console.log("done");
它是:
calling routing navigate
true
done
但是页面上什么也没有发生。登录页面保持不变,用户不会被路由到 /connect 页面,导航栏上的登录按钮继续(即使它等于 !isLogged)。
然后,我按 F5,一切正常。您对导致这种行为的原因有什么想法吗?
我的 app.module.ts:
const appRoutes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'register', component: RegistrationFormComponent },
{ path: 'login', component: LoginFormComponent },
{ path: 'logout', component: LogoutComponent},
{ path: 'connect', component: ConnectorComponent, canActivate: [AuthGuard]},
{ path: '**', redirectTo: 'home' }
]
@NgModule({
declarations: [
AppComponent,
LoginFormComponent,
LogoutComponent,
ConnectorComponent,
HomeComponent
],
providers: [AuthGuard, ConfigService, UserService, AuthModule],
imports: [
CommonModule,
HttpModule,
FormsModule,
DashboardModule,
AuthModule,
RouterModule.forRoot(appRoutes)
]
})
【问题讨论】:
-
您在控制台中看到任何错误吗?路由不显示的主要原因是生成了错误或路由配置不正确。您的连接路由是如何配置的?
-
你有没有在index.html页眉中设置
<base href="/"> -
@DeborahK 控制台上没有错误。我所有的路线都在我的主模块上,并且当我直接从浏览器进入时可以正常工作。有时,当我一直按登录时,页面最终会更改 (?)。
-
@ModarNa 你能解释一下吗?我不在其他组件上使用它,一切正常。我试试看。
-
你能显示包含你的路由配置的模块代码吗?
标签: angular authentication jwt