Angular 2 在登录时导航到不同的页面

Angular 2 navigate to a different page on login

我正在开发一个登录页面。成功登录后,用户将被重定向到另一个页面。在表单中,我保留了表单属性method="post",因为我不想让用户名和密码出现在url上。但是,在成功登录后,当执行 this.router.navigate(['post']); 时,出现错误 "cannot POST /post".

如果我写 method="get",一切正常,但用户名和密码出现在 url 上。请让我知道处理此问题的正确方法是什么:

login.component.ts

import { Component, trigger, state, style, transition, animate } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AuthenticatorService } from './authenticator.service';
import { Router } from '@angular/router';

@Component({
    selector: 'login',
    templateUrl: 'template/login.html',
    animations: [
        trigger('heroState', [
            state('inactive', style({
                height: '0',
                paddingTop: '0',
                paddingBottom: '0',
                marginTop: '0',
                marginBottom: '0',
                visibility: 'hidden',
                overflowY: 'hidden'
            })),
            state('active', style({

            })),
            transition('inactive => active', animate('300ms ease-in')),
            transition('active => inactive', animate('300ms ease-out'))
        ])

    ]
})
export class LoginComponent {

    private formGroup: FormGroup;
    private authenticated = false;
    private loginErrorMessage = 'inactive';
    constructor(formBuilder: FormBuilder, private authenticator: AuthenticatorService, private router: Router) {
        this.formGroup = formBuilder.group({
            username: ['', [Validators.required, Validators.minLength(3)]],
            password: ['', Validators.required]
        });
    }

    onClick() {
        this.authenticated = this.authenticator.authenticate(this.formGroup.controls["username"].value, this.formGroup.controls["password"].value);
        this.loginErrorMessage = this.authenticated?'inactive':'active';
        setTimeout(()=>{
            if(this.loginErrorMessage === 'active') {
                this.loginErrorMessage='inactive';
            }
        },3000);
        if(this.authenticated) {
            this.router.navigate(['post']);
        }
    }

    getLoginStatus() {
        return this.loginErrorMessage;
    }
}

属于login.html

的一部分
    <form [formGroup]="formGroup" role="form" action="" method="post" class="login-form">
        <div *ngIf="formGroup.controls.username.touched && formGroup.controls.username.errors && formGroup.controls.username.errors.required" class="error-text">Username is required</div>
        <div *ngIf="formGroup.controls.username.touched && formGroup.controls.username.errors && formGroup.controls.username.errors.minlength" class="error-text">Username must be atlease three characters long</div>
        <div class="form-group">
            <label class="sr-only" for="form-username">Username</label>
            <input formControlName="username" type="text" name="form-username" placeholder="Username..." class="form-username form-control" id="form-username">
        </div>
        <div class="form-group">
            <label class="sr-only" for="form-password">Password</label>
            <input formControlName="password" type="password" name="form-password" placeholder="Password..." class="form-password form-control" id="form-password">
        </div>
        <button [disabled]="!formGroup.valid" (click)="onClick()" type="submit" class="btn">Sign in!</button>
    </form>

当您调用 this.router.navigate(['post']); 时,您试图告诉路由器导航到 URL hostname/post 并加载相应的组件。

您有一个名为 post 的组件,这是一个非常糟糕的做法,因为名称选择得不好,或者您没有理解路由器的正确用法。


要执行您想要的操作,您需要在登录组件上设置 submit() 方法,以便执行 http.post() 调用并订阅结果以了解身份验证是否成功或不是;然后管理你的路由器,在你认证成功后加载你想要访问的组件。

您应该从官方文档中查看表单提交和路由与导航: https://angular.io/docs/ts/latest/guide/router.html#!#route-config

其他回答很有用,帮我解决了问题。但是,我在这里发布了解决问题的实际修复方法。

我不得不删除提交按钮上的 (click)="onClick()" 并将 (ngSubmit)="onClick()" 添加到表单元素。

来自 angular documentation 的以下文字有助于理解:

The user should be able to submit this form after filling it in. The Submit button at the bottom of the form does nothing on its own but it will trigger a form submit because of its type (type="submit").

A "form submit" is useless at the moment. To make it useful, we'll update the tag with another Angular directive, NgSubmit, and bind it to the HeroFormComponent.submit() method with an event binding