2016-10-26 105 views
1

我有一個簡單的應用程序連接到firebase。登錄時,我只是想將用戶重定向到他們的個人資料頁面。但是,由於某些奇怪的原因,重定向沒有發生。Angular 2.0 Router.navigate登錄後不重定向

我看看here這聽起來像一個類似的問題,但不幸的是,沒有解決方案。

改變重定向到另一個頁面(沒有auth後衛)似乎工作,所以我想問題在那裏,我只是不知道如何解決它。

這裏是我的代碼,一旦它的用戶招牌叫我的服務:

onLogin() { 
    this.authService.signinUser(this.loginForm.value); 
} 

而且我auth.service.ts

public signinUser(user: User) { 
    firebase.auth().signInWithEmailAndPassword(user.email, user.password) 
     .catch(function (error) { 
      // Handle Errors here. 
      let errorCode = error.code; 
      let errorMessage = error.message; 
      // todo 
      console.log(errorCode); 
      console.log(errorMessage); 
     }); 

     this.router.navigate(['/profile']); //not working 
     //this.router.navigate(['/']); //working 
    } 

這裏是我的app.routing.ts

const APP_ROUTES: Routes = [ 
    { path: '', component: HomeComponent }, 
    { path: 'login', component: LoginComponent }, 
    { path: 'signup', component: SignupComponent }, 
    { path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] }, 

]; 

export const routing = RouterModule.forRoot(APP_ROUTES); 

這裏是我的auth.guard.ts

@Injectable() 
export class AuthGuard implements CanActivate { 
    constructor(private authService: AuthService) {} 

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean { 
     return this.authService.isAuthenticated().first(); 
    } 
} 

整個項目在github上,因此您需要檢查另一個配置。

+0

您是否在控制檯上發現任何錯誤? – Sefa

+0

@SefaÜmitOray絕對沒有,控制檯是乾淨的。唯一有點奇怪的是,如果我重新點擊「登錄」按鈕,它會重定向,但只能在第二次嘗試時使用 – gudthing

+0

@SefaÜmitOray當您登錄時會返回什麼?可以激活(route:ActivatedRouteSnapshot,狀態:RouterStateSnapshot):可觀察 | boolean { return this.authService.isAuthenticated()。first(); }' –

回答

0

終於明白了!我很接近,但正如Jan在他的回答中指出的那樣,在註冊和認證建立之前,導航就是直接發生的。通過點擊.then,我可以在創建用戶後執行操作。

firebase.auth().createUserWithEmailAndPassword(user.email, user.password) 
     .then(success => { 
      this.router.navigate(['/profile']); 
     }) 
     .catch(function (error) {...} 
0

您的authsignInWithEmailAndPassword方法可能返回Observable因此它們被延遲。路由器導航立即發生。嘗試將其包含在subscribe()呼叫中。