问题
I have a simple application connected up to firebase. On login, I simply want to redirect the user to their profile page. However, for some odd reason the redirect is not happening.
I have look here which sounds like a similar problem, but unfortunately, no solution there.
Changing the redirect to another page (one which does not have an auth guard) seems to work, so I guess the problem is there, I just don't know how to fix it.
Here is my code, once the user signs in it calls my service:
onLogin() {
this.authService.signinUser(this.loginForm.value);
}
And my 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
}
Here is my 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);
And here is my 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();
}
}
The full project is on github, incase you need to check another configuration.
回答1:
Your auth or signInWithEmailAndPassword method probably returns Observable so they are delayed. Router navigation happens immediately. Try to include it into subscribe() call.
回答2:
Finally figured it out! I was close, but as Jan pointed in his answer, the navigation happened immediaately, before the signup and authentication was established. By tapping into .then I was able to perform the operation once the user had been created.
firebase.auth().createUserWithEmailAndPassword(user.email, user.password)
.then(success => {
this.router.navigate(['/profile']);
})
.catch(function (error) {...}
来源:https://stackoverflow.com/questions/40270309/angular-2-0-router-navigate-not-redirecting-after-login