2017-10-19 140 views
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) 
    ] 
}) 
+1

您是否在控制檯中看到任何錯誤?路由不會顯示的關鍵原因是產生了錯誤或者路由配置不當。您的連接路線如何配置? – DeborahK

+0

你有沒有在index.html頁面標題中設置'' –

+0

@DeborahK在控制檯上沒有錯誤。我所有的路由都在我的主模塊上,並且當我直接從瀏覽器中運行時,它可以正常工作。有時候,當我一直按住登錄時,頁面最終會改變(?)。 –

回答

0

問題解決了。該問題不在路由中,而是在BehaviorSubject中。

當我被送到/連接,角路由我回到/登錄因爲它不會檢測到被登錄。

,因爲我提供了我的UserService這是造成兩次,所以,我正在尋找我的BehaviorSubject的第二個實例,導致此錯誤。

謝謝大家的幫助。