Capture requests globally in angular 4 and stop if

2019-05-16 16:16发布

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

2条回答
时光不老,我们不散
2楼-- · 2019-05-16 16:45

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);
        }
    }
}
查看更多
Animai°情兽
3楼-- · 2019-05-16 17:05
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);
    });
  }
}
查看更多
登录 后发表回答