Capture requests globally in angular 4 and stop if no internet

空扰寡人 提交于 2020-02-02 04:58:06

问题


I can get the connection status using window.navigator.onLine and using the HttpInterceptor as mentioned below i can get access to requests globally. But how do i cancel a request inside the HttpInterceptor? Or else is there a better way to handle this?

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);
    }
}

回答1:


You were very close to the answer.

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) {
            // if there is no internet, throw a HttpErrorResponse error
            // since an error is thrown, the function will terminate here
            return Observable.throw(new HttpErrorResponse({ error: 'Internet is required.' }));

        } else {
            // else return the normal request
            return next.handle(request);
        }
    }
}



回答2:


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);
    });
  }
}


来源:https://stackoverflow.com/questions/46803534/capture-requests-globally-in-angular-4-and-stop-if-no-internet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!