Angular:错误处理 - 拦截器和模态

D.B*_*D.B 3 error-handling httpclient interceptor angular

我构建了一个 Angular 5 应用程序,它在我每次调用时处理错误。使用 HttpClient 我能够拦截在向服务器发送请求后发生的错误。错误在将请求发送到 API 的服务方法上被拦截,然后当发生错误时,它会被推送到组件以显示带有错误消息的漂亮模式。

我想使用拦截器来实现相同的行为,以便以一种集中的方式处理所有错误。但是我不确定是否可以从拦截器类与组件进行通信,将消息发送给它,以便它可以像当前那样触发模态,或者如何直接从拦截器类触发模态。

这是我目前的逻辑:

组件:

  ....
 export class VerificationComponent implements OnInit {
  //Use to call the modal when errors happen
  @ViewChild('modalError') displayErrorRef: ModalComponent; 

//Method send a request to the api using a service instance _myService
getNextRecord() {

    this.errorMesage = "";
    this._myService.getCandidate()
        .subscribe(candidate => {
            this.loadCandidate = candidate;
            this.userName = this.appService.getUser();
        }, error => {                
            this.errorMesage = <any>error.errorMessage;                
            this.displayErrorRef.show();
        });
   }

}
....
Run Code Online (Sandbox Code Playgroud)

服务:

.....
@Injectable()

export class MyService {

  getCandidate(): Observable<ICandidate> {
    return this._http.get(this._getCandidateUrl, this.jwt())
        .map((response: Response) => <ICandidate>response.json())            
        .catch(this.handleError);
   }


private handleError(error: Response) {        
    if (error.text())
        return Observable.throw({errorMessage:error.text(),erroStatus: error.status });
    else
        return Observable.throw('You are not authorised to get this resource');
    }
}
....
Run Code Online (Sandbox Code Playgroud)

模板:

 <!-- This is a child component to display the error message on the top of 
 this template -->
  .....
<app-modal #modalError>
<div class="app-modal-header">
    Error
</div>
<div class="app-modal-body">
    {{errorMesage}}
</div>
<div class="app-modal-footer">
    <button type="button" class="btn btn-default" (click)="hideModalError()">Logout</button>
    <button type="button" class="btn btn-default"(click)="tryGetNextRecord()">Try Again</button>
</div>
</app-modal>
....
Run Code Online (Sandbox Code Playgroud)

Tja*_*alt 6

对于使用HttpInterceptor的全局错误处理程序示例,您需要以下内容。

  • 错误拦截器
  • 错误服务
  • 自定义错误模式

流程是:

app.module => 注册拦截器。

app.module => 注册错误服务作为提供者。

app.component => 注册显示错误模式的全局错误处理。

YourCustomComponent => 不要订阅 Subject/Observable 的错误

您的主要 app.component 将订阅来自错误服务的任何更新,并使用模态引用相应地显示它们。

应用模块

//other code
const interceptors = [{
    provide: HTTP_INTERCEPTORS,
    useClass: ErrorInterceptor,
    multi: true
}];

const services = [{
    ErrorService
}];

@NgModule({
    //other code
    providers: [
        interceptors,
        services
    ],
    //other code
})
Run Code Online (Sandbox Code Playgroud)

错误服务

@Injectable()
export class ErrorService
{
    private errors = new Subject<string[]>();

    constructor() { }

    public addErrors = (errors: string[]): void =>
        this.errors.next(errors);

    public getErrors = () =>
        this.errors.asObservable();
}
Run Code Online (Sandbox Code Playgroud)

错误拦截器

@Injectable()
export class ErrorInterceptor implements HttpInterceptor
{
    constructor(private errorService: ErrorService)
    {         
    }

    intercept(
        request: HttpRequest<any>,
        next: HttpHandler): Observable<HttpEvent<any>>
    {
        return next.handle(request).do(() => { }, (response) =>
        {
            if (response instanceof HttpErrorResponse)
            {                
                if (response.status === 401)
                {
                    return;
                }                

                if (response.status === 400 &&
                    response.error)
                {
                    this.errorService.addErrors(Array.isArray(response.error) ? response.error : [response.error]);
                    return;
                }

                this.errorService.addErrors([`Your generic error message`]);
            }

            return Observable.throw(response);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

应用组件

export class AppComponent implements OnDestroy
{
    private ngUnsubscribe = new Subject();

    @ViewChild('modalError')
    displayErrorRef: ModalComponent; 

    constructor(private errorService: ErrorService)
    {
        this.initializeErrors();
    }    

    ngOnDestroy()
    {
        this.ngUnsubscribe.next();
        this.ngUnsubscribe.complete();
    }

    private initializeErrors()
    {
        this
            .errorService
            .getErrors()
            .pipe(takeUntil(this.ngUnsubscribe))
            .subscribe((errors) =>
            {
                //this.displayErrorRef.error = errors
                this.displayErrorRef.show();
            });
    }   
}
Run Code Online (Sandbox Code Playgroud)

ngUnsubscribe是在您的主要内容app.component被销毁时自动处理订阅。