【问题标题】:update component with custom error handling in angular 6在 Angular 6 中使用自定义错误处理更新组件
【发布时间】:2019-06-19 23:43:37
【问题描述】:

我正在使用 Angular 6

我创建了一个自定义错误处理程序,扩展了 ErrorHandler 来处理所有网络错误,例如。

import {ErrorHandler, Injectable, Injector} from '@angular/core';
import {HttpErrorResponse} from '@angular/common/http';
import {Router} from '@angular/router';
import {ErrorsService} from '../errors-service/errors.service';
import {ToastrService} from 'ngx-toastr';

@Injectable()
export class ErrorsHandler implements ErrorHandler {

  constructor (
    private injector: Injector,
    private toastr: ToastrService
  ) {}

  handleError(error: Error | HttpErrorResponse) {

    const errorsService = this.injector.get(ErrorsService);

    const router = this.injector.get(Router);

    if (error instanceof HttpErrorResponse) {
      if (!navigator.onLine) {
        // Handle offline error

      } else {
        // Handle HTTP Error
        console.log('Http Error occurred');
        errorsService.log(error);

        if (error.status === 403 || error.status === 401) {
          // Clear credentials to login again
          router.navigate(['/auth/logout']).then();
        }

        if (error.status === 400) {
          if (error.error !== null) {
            // Handle 400 errors
            // Generally validation error.
          }
        } else if (error.status === 404) {
          // resource not available
          message = 'Requested resource does not exists';
        } else {
          // handle other type of errors
          message = `${error.status} - ${error.message}`;
        }

      }
    } else {
      // Client Error Happened
      // Send the error to the server and then
      // redirect the user to the page with all the info
      console.log('Not HttpError occurred');
      errorsService.log(error);
    }
  }
}

此处理程序按预期处理所有错误。但是在组件的HTML中,submit按钮在submitted的状态下被禁用

export class SignupComponent implements OnInit {

  form: FormGroup;
  submitted = false;

  constructor(
      private fb: FormBuilder,
      private auth: AuthService
  ) { }

  ngOnInit() {
    // Initialize form
    this.form = this.fb.group({});
  }

  /**
   * Submit form
   */
  onSubmit() {
    this.submitted = true;

    if (this.form.invalid) {
      this.submitted = false;
      return;
    }

    this.auth.register(this.form.value).subscribe(
        () => {
          // Handle success 200 response
          this.submitted = false;
        }
    );
  }
}

在上述情况下,onSubmit() 向服务发出请求并订阅它。

我想在请求/响应完成后将 submitted 标志重置为 false。处理成功响应和重置 submitted 标志很容易。但由于错误是由自定义错误处理程序处理的,如何重置submitted 标志?

如果我将错误处理放在组件中,则自定义错误处理程序将停止工作。此外,如果我避免使用自定义错误处理程序,那么我将不得不在每个订阅中编写重复代码来处理所有类型的错误,例如 403、404、500 等。

【问题讨论】:

    标签: angular angular-errorhandler


    【解决方案1】:

    假设您使用的是 rxjs 6,也许您可​​以使用在错误/成功发生后运行的 finalize,所以是这样的:

    this.auth.register(this.form.value).pipe(
      finalize(() => this.submitted = false)
    )
    .subscribe(() => {
      // handle succecss 200 response
    })
    

    【讨论】:

      猜你喜欢
      • 2019-01-30
      • 1970-01-01
      • 2018-11-30
      • 2019-04-02
      • 2019-06-25
      • 2019-03-31
      • 1970-01-01
      • 2017-11-03
      • 1970-01-01
      相关资源
      最近更新 更多