角4路由/状态问题
问题描述:
我有一个登录方法user.service.ts文件:角4路由/状态问题
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);
}
即通过登录按钮叫上我的登录-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
但是页面上没有任何反应。登录页面保持不变,用户不会路由到/连接页面,导航栏上的登录按钮会继续(即使它等于!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)
]
})
答
问题解决了。该问题不在路由中,而是在BehaviorSubject中。
当我被送到/连接,角路由我回到/登录因为它不会检测到被登录。
,因为我提供了我的UserService这是造成两次,所以,我正在寻找我的BehaviorSubject的第二个实例,导致此错误。
谢谢大家的帮助。
您是否在控制台中看到任何错误?路由不会显示的关键原因是产生了错误或者路由配置不当。您的连接路线如何配置? – DeborahK
你有没有在index.html页面标题中设置' ' –
@DeborahK在控制台上没有错误。我所有的路由都在我的主模块上,并且当我直接从浏览器中运行时,它可以正常工作。有时候,当我一直按住登录时,页面最终会改变(?)。 –