[英]Angular 2.0 Router.navigate not redirecting after login
我有一個簡單的應用程序連接到firebase。 登錄時,我只想將用戶重定向到他們的個人資料頁面。 但是,由於一些奇怪的原因,重定向沒有發生。
我看這里聽起來像是一個類似的問題,但不幸的是,那里沒有解決方案。
將重定向更改為另一個頁面(沒有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上 ,因為你需要檢查另一個配置。
您的auth
或signInWithEmailAndPassword
方法可能會返回Observable
因此它們會被延遲。 路由器導航立即發生。 嘗試將其包含在subscribe()
調用中。
終於想通了! 我很接近,但正如Jan在他的回答中指出的那樣,在注冊和身份驗證建立之前,導航發生了。 通過挖掘.then
我能一旦用戶已經建立了執行該操作。
firebase.auth().createUserWithEmailAndPassword(user.email, user.password)
.then(success => {
this.router.navigate(['/profile']);
})
.catch(function (error) {...}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.