0
我有一個登錄方法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)
]
})
您是否在控制檯中看到任何錯誤?路由不會顯示的關鍵原因是產生了錯誤或者路由配置不當。您的連接路線如何配置? – DeborahK
你有沒有在index.html頁面標題中設置' ' –
@DeborahK在控制檯上沒有錯誤。我所有的路由都在我的主模塊上,並且當我直接從瀏覽器中運行時,它可以正常工作。有時候,當我一直按住登錄時,頁面最終會改變(?)。 –