【问题标题】:Unable to imperatively route to portal after form submit表单提交后无法强制路由到门户
【发布时间】:2016-10-04 19:13:48
【问题描述】:

一旦我让用户登录到我的应用程序,我想强制重定向到门户页面。但是,当我调用 router.navigate() 时会发生 3 件事... 1) 应用程序重定向到 /portal。 2) 然后应用程序立即再次重定向到 /portal,并使用电子邮件地址和密码作为查询字符串。 3)然后应用程序似乎以某种方式“重置”,失去了 appState.User(完全“忘记”用户已经登录),因此应用程序将我重定向回原始登录页面。这里有什么问题?

这一切都发生在由这个按钮触发的表单 onSubmit 中:

<button type="submit" (click)="onSubmit(Form)">Sign in</button>

这是 onSubmit 代码:

public onSubmit(form: EmailForm): void {
    this.apiLogin.LoginUser(form.EmailAddress, form.Password).subscribe(
        (user: LoginUser) => {
            if(user.UserToken == null) {
                this.addValidationError("Invalid username and/or password.");
            }
            else {
                this.appState.setUser(user);
            }
        },
        (err) => {},
        () => {
            this.router.navigate(['/portal']);
        }
    );
}

这也是我的路线设置...

const appRoutes: Routes = [
    { path: '', component: HomeComponent, pathMatch: 'full' },
    { path: 'portal', component: PortalComponent, canActivate: [AuthGuard] },
    { path: '**', component: PageNotFoundComponent }
];

您可能不需要它,但这是我在门户路由上使用的 AuthGuard 服务。感谢@Sasxa 提供helping me setup this AuthGuard

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private appState: ApplicationState, private router: Router) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        let url: string = state.url;
        return this.checkLogin(url);
    }

    checkLogin(url: string): boolean {
        if (this.appState.User.UserToken) return true;

        this.navToLogin(url);
        return false;
    }

    private navToLogin(redirUrl: string) {
        this.router.navigate(['/']);
    }
}   // end class

【问题讨论】:

    标签: angular typescript angular2-routing


    【解决方案1】:

    我想通了。我犯了一个小错误,使用 (click) 而不是 (ngSubmit)。以这种方式修复:

    (ngSubmit)="onSubmit(Form)"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      • 2015-02-12
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多