@angular/common/http#HttpHandler TypeScript Examples

The following examples show how to use @angular/common/http#HttpHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: unauthorized.interceptor.ts    From Smersh with MIT License 6 votes vote down vote up
intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error && [401, 403].includes(error.status)) {
          this.router.navigateByUrl(DashboardRouter.redirectToList());
        }
        return throwError(error);
      })
    );
  }
Example #2
Source File: rubic-exchange-interceptor.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
intercept(httpRequest: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    if (!httpRequest.url.includes(this.DOMAIN_SUBSTRING)) {
      return next.handle(httpRequest);
    }

    let newRequest = this.setDefaultParams(httpRequest);
    newRequest = this.addIframeHostDomain(newRequest);
    newRequest = this.addTokenHeader(newRequest);
    return next.handle(newRequest);
  }
Example #3
Source File: fake-backend.service.ts    From ng-conf-2020-workshop with MIT License 6 votes vote down vote up
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        this.users = JSON.parse(this.localStorage.getItem('users')) || [];
        return of(null).pipe(mergeMap(() => {
            // login user
            if (request.url.endsWith('/login') && request.method === 'POST') {
                return this.loginHandle(request);
            }

            // register user
            if (request.url.endsWith('/register') && request.method === 'POST') {
                const user = this.getStorageUser(request);
                return this.registerHandle(user);
            }

            // login user with external provider
            if (request.url.endsWith('/extlogin') && request.method === 'POST') {
                const user = this.getStorageExtUser(request);
                return this.registerHandle(user, true);
            }

            // Microsoft-specific OIDC discovery URI
            if (request.url.endsWith('ms-discovery/keys') && request.method === 'GET') {
                return of(new HttpResponse({ status: 200, body: msKeys }));
            }

            return next.handle(request);
        }))
        .pipe(materialize())
        .pipe(dematerialize());
    }
Example #4
Source File: base-injectables.ts    From leapp with Mozilla Public License 2.0 6 votes vote down vote up
mustInjected = (): any[] => [
  PositioningService,
  ComponentLoaderFactory,
  BsModalRef,
  BsModalService,
  HttpClient,
  HttpHandler,
  { provide: AppService, useValue: spyAppService },
  { provide: FileService, useValue: spyFileService },
  { provide: KeychainService, useValue: spyKeychainService },
  { provide: MatSnackBar, useValue: spyMatSnackBar },
  { provide: AppNativeService, useValue: spyElectronService },
  { provide: AppProviderService, useValue: spyLeappCoreService },
  { provide: MessageToasterService, useValue: spyMessageToasterService },
]
Example #5
Source File: api-http.interceptor.ts    From The-TypeScript-Workshop with MIT License 6 votes vote down vote up
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (!req.url.startsWith('/api/')) {
      return next.handle(req);
  }

    const relativeUrl = req.url.replace('/api/', '');
    const newRequest = req.clone({ url: `https://jsonplaceholder.typicode.com/${relativeUrl}` });

    return next.handle(newRequest);
  }
Example #6
Source File: auth-interceptor.ts    From NetCoreTutes with MIT License 6 votes vote down vote up
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    var token = this.authService.getToken();
    if (token) {
      var header = "Bearer " + token;
      var reqWithAuth = req.clone({ headers: req.headers.set("Authorization", header) });
      return next.handle(reqWithAuth);
    }

    return next.handle(req);
  }
Example #7
Source File: auth.interceptor.ts    From svvs with MIT License 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/no-explicit-any
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const accessToken = this.authStorage.getAccessToken()

    if (accessToken) {
      req = req.clone({
        headers: req.headers.set('Authorization', `Bearer ${accessToken}`),
      })
    }
    return next.handle(req)
  }
Example #8
Source File: myhttpinterceptor.ts    From CloudeeCMS with Apache License 2.0 6 votes vote down vote up
intercept(req: HttpRequest<any>, next: HttpHandler) {
    // only intercept requests towards API-GW
    if (req.url.search(environment.API_Gateway_Endpoint) === -1) {
      return next.handle(req);
    } else {

      return from(Auth.currentSession()).pipe(
        switchMap(data => {
          const headers = req.headers.set('Authorization', data.getIdToken().getJwtToken());
          const requestClone = req.clone({ headers });
          return next.handle(requestClone);
        })
      );
    }
  }
Example #9
Source File: default-headers.interceptor.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Get the auth token from the service.

    // Clone the request and replace the original headers with
    // cloned headers, updated with the authorization.
    // const cloneReq = req.clone({
    //   headers: req.headers.set("startTimestamp", Date.now().toString()),
    // });
    const start = Date.now();
    const method = req.method;
    const url = req.urlWithParams;

    // send cloned request with header to the next handler.
    return next.handle(req).pipe(
      tap((response: any) => {
        try {
          if (response instanceof HttpResponse) {
            const t = Date.now() - start;
            console.log(`[${method}] ${url} ${response.status} ${t}ms`);
          }
        } catch (e) {
          console.error(e);
        }
      })
    );
  }
Example #10
Source File: auth.interceptor.ts    From ReCapProject-Frontend with MIT License 6 votes vote down vote up
intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<unknown>> {
    let tokenModel: TokenModel | null = this.localStorageService.get<TokenModel>(
      'tokenModel'
    );

    let newRequest: HttpRequest<any> = request.clone({
      headers: request.headers.set(
        'Authorization',
        `Bearer ${tokenModel?.token}`
      ),
    });

    return next.handle(newRequest);
  }
Example #11
Source File: auth.interceptor.ts    From ngx-admin-dotnet-starter with MIT License 6 votes vote down vote up
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req)
      .pipe(catchError((error: HttpErrorResponse) => {
        if (error.status === 401) {
          this.router.navigate(['auth/login']);
        }
        // TODO: handle 403 error ?
        return throwError(error);
      }));
  }
Example #12
Source File: authorization.interceptor.ts    From alura_angular_rxjs_1 with MIT License 6 votes vote down vote up
intercept(
    original_request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    let requestResult: HttpRequest<any>;
    if (this.isUrlNeedsProAuth(original_request.url)) {
      requestResult = this.appendTokenToRequest(original_request);
    } else {
      requestResult = original_request.clone();
    }
    return next.handle(requestResult);
  }
Example #13
Source File: http-error.interceptor.ts    From angular-padroes-e-boas-praticas with MIT License 6 votes vote down vote up
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError((httpError: HttpErrorResponse) => {
        console.error('Error from interceptor', httpError);
        this.notification.error(httpError.error || 'An unexpected error occurred!');
        return throwError(httpError);
      })
    ) as Observable<HttpEvent<any>>;
  }
Example #14
Source File: auth.interceptor.ts    From budget-angular with GNU General Public License v3.0 6 votes vote down vote up
intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (config.auth === "token" && this.jwt && this.jwt.getToken()) {
      request = this.addToken(request, this.jwt.getToken());
    }

    return next.handle(request).pipe(
      catchError((error) => {
        if (error.status === 401) {
          this.authService.doLogoutAndRedirectToLogin();
        }
        return throwError(error);
      })
    );
  }
Example #15
Source File: auth-interceptor.ts    From bitcoin-s-ts with MIT License 6 votes vote down vote up
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = this._authService.getToken()

    if (token) {
      const cloned = req.clone({
        headers: req.headers.set('Authorization', 'Bearer ' + token)
      })
      return next.handle(cloned)
    } else {
      return next.handle(req)
    }
  }
Example #16
Source File: logging-interceptor.ts    From blockcore-hub with MIT License 6 votes vote down vote up
intercept(req: HttpRequest<any>, next: HttpHandler) {
        const started = Date.now();
        let ok: string;

        // extend server response observable with logging
        return next.handle(req)
            .pipe(
                tap(
                    // Succeeds when there is a response; ignore other events
                    event => ok = event instanceof HttpResponse ? 'succeeded' : '',
                    // Operation failed; error is an HttpErrorResponse
                    error => ok = 'failed'
                ),
                // Log when response observable either completes or errors
                finalize(() => {
                    const elapsed = Date.now() - started;
                    const msg = `${req.method} "${req.urlWithParams}"
             ${ok} in ${elapsed} ms.`;

                    this.log.info(msg);
                })
            );
    }
Example #17
Source File: http-error-interceptor.ts    From careydevelopmentcrm with MIT License 6 votes vote down vote up
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    let handled: boolean = false;

    return next.handle(request)
    .pipe(
      //taking out retry for now because it's even retrying on bad credentials
      //retry(1),
      catchError((returnedError) => {
        let errorMessage = null;
        console.log("Returned error", returnedError.error);

        if (returnedError.error instanceof ErrorEvent) {
          errorMessage = `Error: ${returnedError.error.message}`;
        } else if (returnedError instanceof HttpErrorResponse) {
          errorMessage = `Error Status ${returnedError.status}: ${returnedError.message}`;
          handled = this.handleServerSideError(returnedError);
        } 

        console.error(errorMessage ? errorMessage : returnedError);

        if (!handled) {
          return throwError(returnedError);
        } else {
          return of(returnedError);
        }
      })
    )
  }
Example #18
Source File: basic-auth.interceptor.ts    From angular-10-basic-authentication-example with MIT License 6 votes vote down vote up
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add header with basic auth credentials if user is logged in and request is to the api url
        const user = this.authenticationService.userValue;
        const isLoggedIn = user && user.authdata;
        const isApiUrl = request.url.startsWith(environment.apiUrl);
        if (isLoggedIn && isApiUrl) {
            request = request.clone({
                setHeaders: { 
                    Authorization: `Basic ${user.authdata}`
                }
            });
        }

        return next.handle(request);
    }
Example #19
Source File: error.interceptor.ts    From angular-10-facebook-login-example with MIT License 6 votes vote down vote up
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            if ([401, 403].includes(err.status)) {
                // auto logout if 401 or 403 response returned from api
                this.accountService.logout();
            }

            const error = err.error?.message || err.statusText;
            console.error(err);
            return throwError(error);
        }))
    }
Example #20
Source File: error.interceptor.ts    From angular-10-jwt-authentication-example with MIT License 6 votes vote down vote up
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            if (err.status === 401) {
                // auto logout if 401 response returned from api
                this.authenticationService.logout();
                location.reload(true);
            }

            const error = err.error.message || err.statusText;
            return throwError(error);
        }))
    }
Example #21
Source File: error.interceptor.ts    From angular-10-jwt-refresh-tokens with MIT License 6 votes vote down vote up
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            if ([401, 403].includes(err.status) && this.authenticationService.userValue) {
                // auto logout if 401 or 403 response returned from api
                this.authenticationService.logout();
            }

            const error = (err && err.error && err.error.message) || err.statusText;
            console.error(err);
            return throwError(error);
        }))
    }
Example #22
Source File: error.interceptor.ts    From angular-10-registration-login-example with MIT License 6 votes vote down vote up
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            if ([401, 403].includes(err.status) && this.accountService.userValue) {
                // auto logout if 401 or 403 response returned from api
                this.accountService.logout();
            }

            const error = err.error?.message || err.statusText;
            console.error(err);
            return throwError(error);
        }))
    }
Example #23
Source File: error.interceptor.ts    From angular-10-role-based-authorization-example with MIT License 6 votes vote down vote up
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            if ([401, 403].indexOf(err.status) !== -1) {
                // auto logout if 401 Unauthorized or 403 Forbidden response returned from api
                this.authenticationService.logout();
            }

            const error = err.error.message || err.statusText;
            return throwError(error);
        }))
    }
Example #24
Source File: error.interceptor.ts    From angular-10-signup-verification-boilerplate with MIT License 6 votes vote down vote up
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            if ([401, 403].includes(err.status) && this.accountService.accountValue) {
                // auto logout if 401 or 403 response returned from api
                this.accountService.logout();
            }

            const error = (err && err.error && err.error.message) || err.statusText;
            console.error(err);
            return throwError(error);
        }))
    }
Example #25
Source File: admin-interceptor.ts    From mysql_node_angular with MIT License 6 votes vote down vote up
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<any> {
    if (req.url.includes('users')) {
      const userValue = this.authSvc.userValue;
      const authReq = req.clone({
        setHeaders: {
          auth: userValue.token,
        },
      });
      return next.handle(authReq);
    }
    return next.handle(req);
  }
Example #26
Source File: auth.interceptor.ts    From dating-client with MIT License 6 votes vote down vote up
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return this.store.select(selectAuthToken).pipe(
      first(),
      switchMap(token => {
        const authRequest = !!token
          ? req.clone({ setHeaders: { Authorization: `Bearer ${ token }` } })
          : req;
        return next.handle(authRequest);
      })
    );
  }
Example #27
Source File: i18n.interceptor.ts    From geonetwork-ui with GNU General Public License v2.0 6 votes vote down vote up
intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    request = request.clone({
      setHeaders: {
        'Accept-Language': this.translate.currentLang || DEFAULT_LANG,
      },
    })
    return next.handle(request)
  }
Example #28
Source File: http-error.interceptor.ts    From assetMG with Apache License 2.0 6 votes vote down vote up
intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.error instanceof ErrorEvent) {
          // client-side error
          let errorMessage = `Client Side Error: ${error.error.message}`;
          return throwError(errorMessage);
        }
        if (error.status === 403) {
          this.openErrorDialog(error.error);
        }
        // server-side error
        return throwError(error);
      })
    );
  }
Example #29
Source File: http-interceptor.service.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
intercept(req: HttpRequest<NzSafeAny>, next: HttpHandler): Observable<HttpEvent<NzSafeAny>> {
    const token = this.windowServe.getSessionStorage(TokenKey);
    let httpConfig: CustomHttpConfig = {};
    if (!!token) {
      httpConfig = {headers: req.headers.set(TokenKey, token)};
    }
    const copyReq = req.clone(httpConfig);
    return next.handle(copyReq).pipe(filter(e => e.type !== 0), catchError(error => this.handleError(error)));
  }