以角度4全局捕获请求并在没有互联网时停止
问题描述:
我可以使用window.navigator.onLine
获得连接状态,并使用下面提到的HttpInterceptor,我可以全局访问请求。但是,我如何取消HttpInterceptor内的请求?或者还有更好的方法来处理这个问题吗?以角度4全局捕获请求并在没有互联网时停止
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class InternetInterceptor implements HttpInterceptor {
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
//check to see if there's internet
if (!window.navigator.onLine) {
return //cancel request
}
//else return the normal request
return next.handle(request);
}
}
答
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class InternetInterceptor implements HttpInterceptor {
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).do((event: any) => {
//
}).catch(response => {
//if (response instanceof HttpErrorResponse) {
//check to see if there's internet
if (!window.navigator.onLine) {
return //cancel request
}
//}
return Observable.throw(response);
});
}
}
+0
请给你的答案添加一些解释。 – BlackBeard
您可以使用request.unsubscribe();来阻止http请求。 – Amit
你必须在每个地方都做这个问题 –