Angular 2.0 Router.navigate登录后未重定向 [英] Angular 2.0 Router.navigate not redirecting after login
问题描述
我有一个连接到Firebase的简单应用程序.登录时,我只想将用户重定向到他们的个人资料页面.但是,由于某些奇怪的原因,重定向未发生.
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);
}
还有我的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 上,以防您需要检查其他配置.
The full project is on github, incase you need to check another configuration.
推荐答案
终于明白了!我接近了,但正如Jan在他的回答中指出的那样,导航在建立注册和身份验证之前立即发生.通过点击.then
,我就可以在创建用户后执行该操作.
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) {...}
这篇关于Angular 2.0 Router.navigate登录后未重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!