Angular 2.0 Router.navigate 登录后不重定向 [英] Angular 2.0 Router.navigate not redirecting after login

查看:30
本文介绍了Angular 2.0 Router.navigate 登录后不重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个连接到 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆