2017-10-18 69 views
0

我可以使用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); 
    } 
} 
+0

您可以使用request.unsubscribe();來阻止http請求。 – Amit

+0

你必須在每個地方都做這個問題 –

回答

0
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