处理来自后端API的错误,并以angular 6前端形式显示它们

时间:2018-11-15 06:33:19

标签: angular forms api angular6 handleerror

我正在开发一个注册表单,并与Laravel后端API连接。当我插入新客户的数据时,它成功地将请求发送到后端并重定向到登录页面。当我输入错误数据或现有数据错误时,应在注册表单的输入框下方显示正确的信息。但是现在它没有在表单中显示错误,而是可以在控制台中显示错误。

onSubmit() {
this.appService.signUp(this.form).subscribe(
     data => this.handleResponse(data),
     error => this.handleError(error)
 );
}

这是我的提交按钮的功能,当我评论data => this.handleResponse(data),时,它将在输入框后立即显示来自后端的错误作为警报。当数据和错误都在函数中时,错误不会显示在表格中。我想处理错误,并希望将数据传递给handleResponse函数。

sign-up.component.ts

export class SignUpComponent implements OnInit {

 public form = {
   firstName: null,
   lastName: null,
   email: null,
   mobile: null,
   password: null
 };
 public error = [];

constructor(
  private appService: AppService,
  private token: TokenService,
  private router: Router) { }

onSubmit() {
  this.appService.signUp(this.form).subscribe(
     data => this.handleResponse(data),
   // data => console.log(data),
  error => this.handleError(error)
  );
}

handleResponse(data) {
  console.log(data);
  // this.token.handleToken(data.data.accessToken);
  if (data.code === 'SUCCESS') {
    this.router.navigateByUrl('/login');
    }
}

handleError(code) {
  this.error = code.data;
   console.log(code.data);
}

ngOnInit() {
}

}

sign-up.component.html

<div class="mt-4 col-8 offset-2">
<div class="card">
 <div class="card-header">Register Here</div>
 <div class="card-body">
  <form #signupForm =ngForm (ngSubmit)="onSubmit()">
    <div class="form-group row">
      <label for="inputFirstName3" class="col-sm-2 col-form-label">First Name</label>
      <div class="col-sm-10">
        <input type="text" name="firstName" class="form-control" id="inputFirstName3" placeholder="First Name" [(ngModel)]="form.firstName" required>
        <div class="alert alert-danger" [hidden]="!error.firstName">{{error.firstName}}</div>
      </div>
    </div>

    <div class="form-group row">
      <label for="inputLastName3" class="col-sm-2 col-form-label">Last Name</label>
      <div class="col-sm-10">
        <input type="text" name="lastName" class="form-control" id="inputLastName3" placeholder="Last Name" [(ngModel)]="form.lastName" required>
        <div class="alert alert-danger" [hidden]="!error.lastName">{{error.lastName}}</div>
      </div>
    </div>

    <div class="form-group row">
      <label for="inputEmail3" class="col-sm-2 col-form-label">Email</label>
      <div class="col-sm-10">
        <input type="email" name="email" class="form-control" id="inputEmail3" placeholder="Email" [(ngModel)]="form.email" required>
        <div class="alert alert-danger" [hidden]="!error.email">{{error.email}}</div>
      </div>
    </div>

    <div class="form-group row">
      <label for="inputMobile" class="col-sm-2 col-form-label">Mobile</label>
      <div class="col-sm-10">
        <input type="text" name="mobile" class="form-control" id="inputMobile" placeholder="Mobile" [(ngModel)]="form.mobile" required>
        <div class="alert alert-danger" [hidden]="!error.mobile">{{error.mobile}}</div>
      </div>
    </div>

    <div class="form-group row">
      <label for="inputPassword3" class="col-sm-2 col-form-label">Password</label>
      <div class="col-sm-10">
        <show-hide-password size="small" icon="icon-eye" btnStyle="default" [btnOutline]="false">
          <input type="password" name="password" class="form-control" id="inputPassword3" placeholder="Password" [(ngModel)]="form.password" required>
        </show-hide-password>
        <div class="alert alert-danger" [hidden]="!error.password">{{error.password}}</div>
      </div>
    </div>

    <div class="form-group row">
      <div class="col-sm-10 offset-2">
        <button type="submit" class="btn btn-primary" [disabled]="!signupForm.valid">Sign up</button>

        <a routerLink="/login" class="btn btn-info float-right">Sign in</a>
      </div>
    </div>
  </form>
</div>

app.service.ts

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Injectable({
 providedIn: 'root'
 })
export class AppService {

 private baseUrl = 'http://dev.api.prestotestlabs.com/api';
 constructor(private http: HttpClient) { }

 signUp(data) {
  return this.http.post(`${this.baseUrl}/customers`, data);
 }

login(data) {
  return this.http.post(`${this.baseUrl}/login`, data);
 }
}

token.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class TokenService {

private iss = {
  login: 'http://dev.api.prestotestlabs.com/api/login',
  signup: 'http://dev.api.prestotestlabs.com/api/customers',
};
constructor() { }

handleToken(token) {
  this.set(token);
  // console.log(this.isValid());
}

set(token) {
  localStorage.setItem('token', token);
  // console.log(this.get());
}

get() {
 return localStorage.getItem('token');
}

remove() {
  localStorage.removeItem('token');
}

isValid() {
  const token = this.get();
  if (token) {
    const payload = this.payload(token);
  if (payload) {
    return Object.values(this.iss).indexOf(payload.iss) > -1 ? true : false;
   }
  }
  return false;
 }

payload(token) {
  const payload = token.split('.')[1];
  return this.decode(payload);
}
decode(payload) {
  return JSON.parse(atob(payload));
}
loggedIn() {
  return this.isValid();
 }
}

1 个答案:

答案 0 :(得分:0)

您可以使用“尝试捕获错误处理”来处理错误状态,也可以使用HttpClient请求的订阅响应作为波纹管。我不确定这是否是最合适的答案,但是它能满足我的要求。

onSubmit() {
 this.toastrService.success('', 'Processing...', {timeOut: 9500});
 this.registerSubs = this.userAuthenticationService.register(this.model)
  .catch((err: any) => {
    this.toastrService.toasts.forEach(toast => {
      this.toastrService.clear(toast.toastId);
    });

    return Observable.empty<T>();
  }).
subscribe(response => {
    this.toastrService.toasts.forEach(toast => {
      this.toastrService.clear(toast.toastId);
    });
  if (response !== null && response.code === 'SUCCESS') {
    this.toastrService.success('One more step to complete registration!');
    this.viewService.headerChange.next(true);
    this.router.navigateByUrl('/otp-verification');
    window.scrollBy(0, 10);
    this.viewService.closeSideMenu.next();
  } else if (response !== null && response.code === 'VALIDATION_FAILED') {
    this.toastrService.error(this.generateErrorMessages(response.data));
  } else if (response !== null && response.code === 'FAIL'){
    this.toastrService.error(response.message);
  }else {
  }
});
}


generateErrorMessages(errors: any[]) {
let errorString = '';
if ((<any>errors).email !== null && typeof((<any>errors).email) !== 'undefined') {
  errorString += (<any>errors).email;
}
if ((<any>errors).mobile !== null && typeof((<any>errors).mobile) !== 'undefined') {
  errorString += (<any>errors).mobile;
}

return errorString;
}