1

我正在使用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 中,提交按钮在提交状态下被禁用,例如

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()向服务发出请求并订阅它。

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

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

4

1 回答 1

1

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

this.auth.register(this.form.value).pipe(
  finalize(() => this.submitted = false)
)
.subscribe(() => {
  // handle succecss 200 response
})
于 2019-01-26T13:44:02.590 回答