Angular 4 on submit显示错误基于服务器的响应

时间:2017-07-18 03:02:47

标签: forms angular typescript

当表单提交并返回错误状态代码时,我花了几个小时尝试显示错误。我似乎无法弄清楚这一点......

以下评论中的登录表单组件我显示了id告诉表单它无效或有效的地方。

import { Component, OnInit, Input, Output, EventEmitter  } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators, NgForm } from "@angular/forms";
import { AuthenticationService } from "../../../services/authentication.service";
import { User } from "../../../domain/user";


@Component({
  selector: 'login-form',
  templateUrl: './login-form.component.html'
})
export class LoginFormComponent implements OnInit {

  loginForm: FormGroup;
  post: any;
  username: string;
  password: string;
  user: User;
  errorMessage: string  = '';


  constructor(private fb: FormBuilder, private router: Router, private authenticationService: AuthenticationService) {
    this.loginForm = fb.group({
      'username': [null, Validators.required],
      'password': [null, Validators.required],
      'login': false
    });
  }


  ngOnInit() {
    this.authenticationService.logout(); // reset login status
  }


  login(values) {
    this.username = values.username;
    this.password = values.password;

    this.authenticationService.login(this.username, this.password)
      .subscribe(result => {
          if (result === true) {
            this.router.navigate(['/']);
            localStorage.setItem('currentUser', JSON.stringify(this.user));
            // here form should be valid
          } else {
            this.errorMessage = 'Username or password is incorrect';
            // here form should be invalid
          }
      });
  }
}

登录表单Html,第二个<div>是表单提交后显示的错误ID。

<form id="loginForm" [formGroup]="loginForm" (ngSubmit)="login(loginForm.value)" novalidate>
  <div class='form-text error' *ngIf="submitted">
    <div *ngIf="loginForm.invalid" class="help-block error small">Username or password is incorrect.</div>
  </div>
  <div class="form-group">
    <label class="control-label" for="username">Username</label>
    <input type="text" placeholder="Please enter your usename" title="Please enter you username" required value=""
           id="username" class="form-control" name="username" formControlName="username">
    <div class='form-text error' *ngIf="loginForm.controls.username.touched">
      <div *ngIf="loginForm.controls.username.hasError('required')" class="help-block error small">Username is required.</div>
    </div>
    <span *ngIf="loginForm.controls.username.valid || !loginForm.controls.username.touched"  class="help-block small">Your unique username</span>
  </div>
  <div class="form-group">
    <label class="control-label" for="password">Password</label>
    <input type="password" title="Please enter your password" placeholder="******" required value=""
           id="password" class="form-control" name="password" formControlName="password">
    <div class='form-text error' *ngIf="loginForm.controls.password.touched">
      <div *ngIf="loginForm.controls.password.hasError('required')" class="help-block error small">Password is required.</div>
    </div>
    <span *ngIf="loginForm.controls.password.valid || !loginForm.controls.password.touched" class="help-block small">Your strong password</span>
  </div>
  <div>
    <button type="submit" class="btn btn-accent" [disabled]="!loginForm.valid">Login</button>
    <a class="btn btn-default" routerLink="/register">Register</a>
  </div>
</form>

2 个答案:

答案 0 :(得分:4)

来自服务器端的错误,您的表单在此处有效。因此,在失败处理程序中将flag设置为false。

组件:

首先为它做一个变量:

export class LoginFormComponent implements OnInit {

  loginForm: FormGroup;
  post: any;
  username: string;
  password: string;
  user: User;
  errorMessage: string  = '';
  authenticationFlag: boolean = true;

并在您的登录方式中:

login(values) {
    this.username = values.username;
    this.password = values.password;

    this.authenticationService.login(this.username, this.password)
      .subscribe(result => {
          if (result === true) {
            this.router.navigate(['/']);
            localStorage.setItem('currentUser', JSON.stringify(this.user));
            // here form should be valid
          } else {
             this.authenticationFlag = false;
          }
      });
  }

HTML模板:

更改此代码:

<div class='form-text error' *ngIf="submitted">
    <div *ngIf="loginForm.invalid" class="help-block error small">Username or password is incorrect.</div>
</div>

由此:

<div *ngIf="!authenticationFlag" class="help-block error small">Username or password is incorrect.</div>

答案 1 :(得分:1)

因此,在我的身份验证服务类中,我没有正确处理错误。我在身份验证服务中更改了我的登录方法以包含catch。

  login(username: string, password: string): Observable<boolean> {
    let user = JSON.stringify({ username: username, password: password });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.loginUrl, user, options)
      .map(function(res){
        let data = res.json();
        alert(res.status);

        if (data) {
          this.token = data.token;
          localStorage.setItem('currentUser', JSON.stringify({ username: username, token: this.token }));
          return true; // successful login
        } else {
          return false; // failed login
        }
      })
      .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
  }

然后在我的登录表单组件中,我将auth服务登录方法的使用更改为:

  login(values) {
    this.username = values.username;
    this.password = values.password;

    this.authenticationService.login(this.username, this.password)
      .subscribe(result => {
          if (result === true) {
            this.router.navigate(['/']);
            localStorage.setItem('currentUser', JSON.stringify(this.user));
          }
      },
      err => {
        this.authenticationFlag = false;
      });
  }
正如@Wasif Khan所说,我所需要的只是一个组件变量。这个评论太长了。