import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse, HttpHeaders, HttpErrorResponse} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import {NgbModal} from '@ng-bootstrap/ng-bootstrap';
import { ErrormodalComponent } from '../../features/errormodal/errormodal.component';
import { UploadComponent } from '../../features/upload/upload.component';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private _ngbModal: NgbModal) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).do((event: HttpEvent<any>) => {
// What to do here?
}, (err: any) => {
if(err instanceof HttpErrorResponse) {
switch(err.status) {
case 404:
// API not found
console.log('launch')
this._ngbModal.open(UploadComponent, {size: 'lg', backdrop: 'static' })
break
}
console.log('err', err)
}
})
}
}
我得到了错误部分,但在正常的,无错误的请求/响应的情况下,如果我What to do here?
我该怎么办?
答案 0 :(得分:1)
我建议使用catch运算符而不是do:
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse, HttpHeaders, HttpErrorResponse} from '@angular/common/http';
import { Observable } from 'rxjs';
import {NgbModal} from '@ng-bootstrap/ng-bootstrap';
import { ErrormodalComponent } from '../../features/errormodal/errormodal.component';
import { UploadComponent } from '../../features/upload/upload.component';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private _ngbModal: NgbModal) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).catch((err : HttpErrorResponse) => {
switch(err.status) {
case 404:
// API not found
console.log('launch')
this._ngbModal.open(UploadComponent, {size: 'lg', backdrop: 'static' })
break
}
console.log('err', err);
return Observable.throw(err);
});
}
}
您需要将ErrorInterceptor服务添加到app模块提供者部分,如此
providers :[
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
]
答案 1 :(得分:1)
Try something like this:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next
.handle(request)
.map((response: HttpEvent<any>) => {
if (response instanceof HttpResponse) {
// Here if you want to parse your response you can do it otherwise just let it flow
return response;
}
})
.catch((response: HttpEvent<any>) => {
if (response instanceof HttpErrorResponse) {
return response;
}
});
}