2016-10-04 41 views
0

一旦我有用戶登錄到我的應用程序,我想強制重定向到門戶頁面。然而,當我呼叫router.navigate()時發生了3件事... 1)應用程序重定向到/ portal。 2)然後,該應用立即重定向到/門戶網站,並將電子郵件地址和密碼作爲查詢字符串。 3)該應用程序似乎「重置」以某種方式,失去了appState.User(完全「忘記」用戶已經登錄),所以該應用程序將我重新導向到原始登錄頁面。這裏有什麼問題?無法在表單提交後強制路由到門戶網站

這一切發生的一切形式的onsubmit它獲取此按鈕觸發的內部:

<button type="submit" (click)="onSubmit(Form)">Sign in</button> 

這裏的的onsubmit代碼:

public onSubmit(form: EmailForm): void { 
    this.apiLogin.LoginUser(form.EmailAddress, form.Password).subscribe(
     (user: LoginUser) => { 
      if(user.UserToken == null) { 
       this.addValidationError("Invalid username and/or password."); 
      } 
      else { 
       this.appState.setUser(user); 
      } 
     }, 
     (err) => {}, 
     () => { 
      this.router.navigate(['/portal']); 
     } 
    ); 
} 

這是我的路線設置,以及...

const appRoutes: Routes = [ 
    { path: '', component: HomeComponent, pathMatch: 'full' }, 
    { path: 'portal', component: PortalComponent, canActivate: [AuthGuard] }, 
    { path: '**', component: PageNotFoundComponent } 
]; 

您可能不需要它,但這裏是我在門戶路由上使用的AuthGuard服務。謝謝@Sasxa的helping me setup this AuthGuard

@Injectable() 
export class AuthGuard implements CanActivate { 
    constructor(private appState: ApplicationState, private router: Router) {} 

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { 
     let url: string = state.url; 
     return this.checkLogin(url); 
    } 

    checkLogin(url: string): boolean { 
     if (this.appState.User.UserToken) return true; 

     this.navToLogin(url); 
     return false; 
    } 

    private navToLogin(redirUrl: string) { 
     this.router.navigate(['/']); 
    } 
} // end class 

回答

0

我想通了。我使用(點擊)而不是(ngSubmit)犯了一個小錯誤。固定方式:

(ngSubmit)="onSubmit(Form)"