我正在使用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等。
假设您使用的是rxjs 6,也许您可以使用finalize
在发生错误/成功后运行的rxjs,如下所示:
this.auth.register(this.form.value).pipe(
finalize(() => this.submitted = false)
)
.subscribe(() => {
// handle succecss 200 response
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句