标签: angular-http-interceptors

Angular 使用全局拦截器

我想全局使用 2 个拦截器(httpInterceptorProviders、jwtInterceptorProviders),但它在我的惰性模块中不起作用。我有 CoreModule 和 X 延迟加载模块。奇怪的是,我有一个由 swagger 生成器(http 服务)自动生成的代码,该调用被拦截,但是当我使用自定义 http 服务拦截器时,不会拦截该请求。

Index.ts 我在哪里获取提供程序

/** Http interceptor providers in outside-in order */
export const httpInterceptorProviders = [
    { provide: HTTP_INTERCEPTORS, useClass: HttpErrorInterceptor, multi: true }
];

export const jwtInterceptorProviders = [
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }
];
Run Code Online (Sandbox Code Playgroud)

CoreModule,我在提供程序中导入拦截器

/** Http interceptor providers in outside-in order */
export const httpInterceptorProviders = [
    { provide: HTTP_INTERCEPTORS, useClass: HttpErrorInterceptor, multi: true }
];

export const jwtInterceptorProviders = [
    { provide: …
Run Code Online (Sandbox Code Playgroud)

javascript multipartform-data typescript angular-http-interceptors angular

2
推荐指数
1
解决办法
5501
查看次数

使用 Angular HTTP 拦截器管理多个同时异步服务调用的加载器/旋转器

我已经实现了 Http 拦截器,并在服务启动时显示微调器,并在服务成功/失败时隐藏微调器。

代码示例:

        intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

             return next.handle(req).pipe(
                tap((event: HttpEvent<any>) => {
                    if (event instanceof HttpResponse && event.body.errCode != undefined) {
                        // show_spinner

                    }
                }),
                finalize(()=>{
                    // hide_spinner
             })
         }
Run Code Online (Sandbox Code Playgroud)

例如,有两个服务调用同时发生;因此,将显示与两个调用相对应的微调器,但第一个服务在2 秒内完成,第二个服务在5 秒内完成;现在,旋转器将在第一个调用完成后隐藏,将无法确认第二个服务调用。

httprequest interceptor rxjs angular-http-interceptors angular

2
推荐指数
1
解决办法
3754
查看次数

为Angular 4中的每个Http请求创建全局身份验证标头

当我从api得到一些东西时,我想让授权标题不要一次又一次地声明它.

每当我需要从api获取数据时,我需要附加授权标头.我目前在Angular 4中使用HTTPCLIENT.我的代码:

auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/map';
import { AppSettings } from '../app.constants';


@Injectable()
export class AuthService {
  private loggedIn = false;

  constructor(private httpClient: HttpClient) {
  }

  loginUser(email: string, password: string) {  
    const headers = new HttpHeaders() 
    .set('Content-Type', 'application/json');

    return this.httpClient
    .post(
       GLOBAL_URL.LOGIN_URL + '/auth/login', 
       JSON.stringify({ email, password }), 
       { headers: headers }
    )
    .map(
        (response: any) => {
         localStorage.setItem('auth_token', response.token);
          this.loggedIn = true;
          return response;
        });
   } …
Run Code Online (Sandbox Code Playgroud)

angular-http angular-http-interceptors angular angular-httpclient

1
推荐指数
1
解决办法
1474
查看次数

Angular 4和OAuth-拦截401响应,刷新访问令牌并重试请求

如标题所示,我正在使用OAuth身份验证开发Angular 4项目。

每当http请求以状态代码401响应时,我都会拦截该请求,更新访问令牌并重试失败的请求。

当我收到401消息时,请求将被正确拦截,访问令牌将按应有的方式刷新。失败的请求也将再次执行,但不再将其响应传递给组件。

因此,问题在于应该在刷新令牌和重试请求之前,应在请求响应上观察的我的组件抱怨该视图的日志“接收属性错误”。

我的拦截器:

import { Injectable, Inject, Injector } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpResponse,
  HttpErrorResponse,
  HttpEvent,
  HttpInterceptor,
  HttpSentEvent,
  HttpHeaderResponse,
  HttpProgressEvent,
  HttpUserEvent
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { TokenManager } from '../../../util/TokenManager';
import { AuthUserResponse } from '../../../models/authUserResponse';
import 'rxjs/add/operator/switchMap';

@Injectable()
export class AuthTokenExpiredInterceptor implements HttpInterceptor {

  isRefreshingToken: boolean = false;
  tokenSubject: BehaviorSubject<string> = new BehaviorSubject<string>(null);

  constructor( private injector: …
Run Code Online (Sandbox Code Playgroud)

typescript angular-http-interceptors angular

1
推荐指数
1
解决办法
2662
查看次数

拦截器中的 Angular http 请求时间

我正在制作一个拦截器来记录我的 http 请求。

到目前为止,一切都很好,一切都按预期工作。

我现在想要的是获取执行请求所需的时间。

我以为我可以做这样的事情

const start = Date.now();
return next
  .handle(req)
  .map(res => {
    console.log('took ' + (Date.now() - start) + 'ms');
    return res;
  })
Run Code Online (Sandbox Code Playgroud)

}

但是控制台显示1到2ms,而网络显示超过50ms......我认为我应该在创建请求时创建起始值,但我不知道如何。

任何解决方案?

PS:我的 linting 配置禁止我使用console.time()

javascript angular-http-interceptors google-chrome-console angular

1
推荐指数
1
解决办法
3298
查看次数

带有自定义标头的单元测试拦截器

我一直在尝试在 Angular 6 的拦截器中运行一个测试单元,但是经过多次反复试验后,我不断收到以下错误:

错误:应为条件“按功能匹配:”的匹配请求,但未找到。

我对 NG6 和单元测试有点陌生,在文档中找不到任何内容

这是我得到的:

令牌服务(它被嘲笑,因为它与后端没有联系)

export class TokenService {

token: EventEmitter<any> = new EventEmitter();

findTokenData(): Observable<any> {

    return Observable.create((observer: Observer<object>) => {
        observer.next({ headerName: x-fake, token: fake' });
        observer.complete();
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

休息拦截器

export class RestInterceptor implements HttpInterceptor {

constructor(public tokenService: TokenService) { }

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    console.log('request intercepted...');

    let authReq: HttpRequest<any>;
    const customHeadersMethods = ['POST', 'PUT', 'DELETE', 'PATCH'];

    // If the requested method is different GET or HEAD request the CSRF …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing jasmine angular-http-interceptors angular

1
推荐指数
1
解决办法
2576
查看次数

Angular 7拦截器更改标头并再次重试请求

我正在尝试处理响应标头,在某些特定情况下,当刷新令牌从后端发送时,用新令牌替换标头中的旧令牌并再次发送请求。经过数小时的研究,我没有找到任何适用于 Angular 7 的解决方案。我成功拦截请求,但未能成功替换令牌并再次发送相同的请求。

我这样做:

    export class RefreshTokenInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).pipe(
            tap(event => {

            },
            (error: any) => {
                if (error.status == 401 && error.error.token) {
                    // what to do here
                    // error.error.token is new generated token
                }
            })
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏。

http-headers angular-http-interceptors angular angular7

1
推荐指数
1
解决办法
4902
查看次数

Angular-7-拦截器-令牌刷新后重试请求

我正在尝试为令牌过期时失败的请求实现拦截器。我尝试了多种方法但仍然没有成功。

我已经参考了下面的 URL 并阅读了多个博客。每个人都建议切换地图方法,但不与我合作。 Angular 4拦截器在令牌刷新后重试请求

我尝试将所有请求收集到cachedRequests中:Array> = []; 但不知道如何使用它来重新触发失败的请求。

成功刷新令牌后, this.next.handle(request) 不会被召回。不过我可以看到更新后的请求对象。

有人可以指出在角度7中用
“rxjs”:“〜6.3.3”,“rxjs-compat”:“^ 6.5.2”引用的地方,以实现拦截器。

下面是对我有用但仅获得令牌响应的代码

``````````
    handleError(request: HttpRequest<any>, next: HttpHandler, err) {
            if (err instanceof HttpErrorResponse) {
                if (err.status === 401) {
                    this.service.getNewToken().pipe(filter(token => token != null),
                        take(1),
                        switchMap((token: any) => {
                            console.log('token', token);
                            if (token && token.access_token && token.refresh_token) {
                                sessionStorage.setItem('accessToken', token.access_token);
                                sessionStorage.setItem('refreshToken', token.refresh_token);
                            }
                            request = this.addHeader(request);
                            request.headers.getAll('Authorization');
                            return next.handle(request);
                        })).subscribe(results => this.subject.next(results));

                }
            }
        }

`````````
Run Code Online (Sandbox Code Playgroud)

更新2:尝试多种方法后我发现

  1. 返回 next.handle(请求); <-- 这根本就没有被调用
  2. 返回 next.handle(request).subscribe(); <-- 这被调用但不更新对请求的组件的响应。 …

angular-http-interceptors angular angular7

1
推荐指数
1
解决办法
3545
查看次数

无法在AngularJS控制器中捕获事件

我正在尝试实现用户身份验证系统.我读过有关401http状态代码和HTTP Auth拦截器模块的文章.

我已经用bower下载了模块并将其加载到我的app模块中.我还没有使用它但是我想使用当用户在浏览器中打开应用程序时该模块触发的相同事件来显示用户登录弹出窗口.

我所有的控制者都是孩子的CoreController.该CoreController解决当前用户.当应用程序加载时没有用户登录,因此我想显示发出事件的登录表单:( event:auth-loginRequired与http-auth-interceptor相同).

在这个CoreController我有另一个规则,正在侦听这个特定的事件(event:auth-loginRequired).如果检测到此事件,控制器将显示调用其stateid 的弹出窗口.

我的问题是,控制台是说,我已经正确地发出该事件,但我的听众不会被触发,因此登录弹出没有显示.

这是我的CoreController:

/**
 * Index controller definition
 *
 * @scope Controllers
 */
define(['./../module', 'moment'], function (controllers, moment) {
    'use strict';

    controllers.controller('CoreController', ['$scope', '$rootScope', '$state', 'user', function ($scope, $rootScope, $state, user)
    {
        console.log('Core Controller Loaded');
        $scope.loader = true;

        $scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams)
        {
            $scope.loader = true;
        });

        $scope.$on('event:auth-loginRequired', function(event, toState, toParams, fromState, fromParams)
        {
            console.log('catch …
Run Code Online (Sandbox Code Playgroud)

angularjs angularjs-scope angular-http-interceptors

0
推荐指数
1
解决办法
4979
查看次数

Angular 4 HttpInterceptor刷新令牌

我有HttpInterceptor:

import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, 
HttpRequest} from '@angular/common/http';
import {AuthService} from '../service/auth.service';
import {Observable} from 'rxjs/Observable';
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private authService: AuthService,
              private router: Router) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler):     Observable<HttpEvent<any>> {
    const clone = request.clone({headers: request.headers.set(AuthService.AUTH, this.authService.getToken())});
    return next.handle(clone).catch(error => {
      if (error instanceof HttpErrorResponse && error.status === 401) {
        this.authService.clearToken();
        this.router.navigate(['/auth/signin']);
        return Observable.empty();
      }
      return Observable.throw(error);
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

我想在if块中刷新令牌,但是当我 …

interceptor angular-http-interceptors angular

0
推荐指数
1
解决办法
863
查看次数

Angular 4.3x 动态 http 拦截器

我按照medium中的这篇文章创建了一个http拦截器,它可以让我向每个http调用添加标头

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(public auth: AuthService) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${this.auth.getToken()}`
      }
    });
    return next.handle(request);
  }
}
Run Code Online (Sandbox Code Playgroud)

本文使用 authService 动态获取令牌。然而,一旦我将 HttpClient 注入 AuthService 中,我就会收到循环注入错误。

还有其他方法可以动态调整拦截器吗?

typescript angular-http-interceptors angular

0
推荐指数
1
解决办法
3180
查看次数

刷新令牌OAuth身份验证Angular 4+

我正在使用HttpAngular HttpClient的解决方案,但是我决定进行迁移并使用新的解决方案,并且我试图创建一种解决方案Interceptors来管理需要刷新令牌以及需要将标头修改为放置授权令牌。

http interceptor angular-http-interceptors angular

0
推荐指数
1
解决办法
8732
查看次数

Angular 5 拦截 - 请求重复

我在 Angular 5 中使用了带有 HttpInterceptor 的拦截器,并且我在使用 rxjs 时遇到了问题,其中我的所有 http 请求都重复了。

import { Router } from '@angular/router';
import { Injectable, ApplicationRef } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/empty';
import { NgxSpinnerService } from 'ngx-spinner';
import { ErrorHandlingService } from '../../service/error-handling.service';

@Injectable()
export class ApiRequestInterceptor implements HttpInterceptor {

  private count: number = 0;

  constructor(
    private readonly spinner: NgxSpinnerService,
    private readonly router: Router,
    private readonly …
Run Code Online (Sandbox Code Playgroud)

rxjs angular-http-interceptors angular angular5

0
推荐指数
1
解决办法
1682
查看次数