标签: angular-http-interceptors

检测Angular JavaScript promise链中是否存在下一个处理程序

给出以下两个$resource例子:

var exampleOne = $resource('/path').save(objectOne);
exampleOne.$promise.then(function (success) {}, function (error) {});

var exampleTwo = $resource('/path').save(objectTwo);
exampleTwo.$promise.then(function (success) {});
Run Code Online (Sandbox Code Playgroud)

[注意:示例二不包含错误处理程序]

以及位于所有$http请求下方的拦截​​器:

var interceptor = ['$location', '$q', function ($location, $q) {
   function error(response) {
       if (response.status === 400) {
           return $q.reject(response);
       }
       else {
           $location.path('/error/page');
       }
       return $q.reject(response);
   }

   return {
       'responseError': error
   };
}

$httpProvider.interceptors.push(interceptor);
Run Code Online (Sandbox Code Playgroud)

当示例资源不$promise.then()包含错误回调时,如何使拦截器不被拒绝?如果回调存在,exampleOne那么我希望拒绝,但如果没有,exampleTwo那么我希望重定向到错误页面,从而将条件更改为:

if (response.status === 400 && $q.unresolvedPromises.doIndeedExist()) { ...
Run Code Online (Sandbox Code Playgroud)

为什么?因为我的项目中只有一些情况需要以400用户友好的方式处理,所以我想消除许多重复的错误回调或者必须在拦截器中放置一个不常见的情况列表.我希望拦截器能够根据promise链中另一个处理程序的存在来决定.

javascript promise angularjs angular-http-interceptors

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

角度在Cordova上表现不同

我正在构建一个角度应用程序,其中有几个模块靠近john papas styleguide.接下来,我有几个独立的模块,有自己的路由定义,有些有拦截器.我的问题是:当我在Cordova/Android上运行时,当我将它们放在主模块中时,状态定义似乎才有效.在我的浏览器中工作.有没有人来过这个问题呢?

例如,这适用于本地浏览器和带有cordova的设备:

//main.js
'use strict';
angular.module('main', [
  'app.core',
  'auth'
])
.config(function ($stateProvider, $urlRouterProvider) {
  // ROUTING with ui.router
  $urlRouterProvider.otherwise('/main/list');
  $stateProvider
    // this state is placed in the <ion-nav-view> in the index.html
    .state('main', {
      url: '/main',
      abstract: true,
      templateUrl: 'main/templates/menu.html',
      controller: 'MenuCtrl as menu'
    })
  .state('main.login', {
    url: '/login',
    views: {
      'pageContent': {
        templateUrl: 'auth/templates/auth.login.html',
        controller: 'LoginCtrl'
      }
    }
  })
/* more states here */
Run Code Online (Sandbox Code Playgroud)

这仅适用于本地浏览器(与上面相同的主模块):

//auth.routes.js
'use strict';

angular
    .module('auth.routes')
    .config(config);

function config ($stateProvider) {
  $stateProvider …
Run Code Online (Sandbox Code Playgroud)

angularjs cordova angular-ui-router angular-http-interceptors

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

Angular 4.3拦截器 - 如何使用?

我正在构建一个需要授权标头的新应用.通常我会使用与此scotch.io文章中的方法非常相似的内容.但是我注意到,现在通过新的HttpClientModule在Angular 4生态系统中完全支持HTTP拦截器,我试图找到一些关于如何使用它们的文档.

如果我不正确(从4.3开始)这是注入授权标题的最佳做法,我也愿意接受建议.我的想法是,它是最近添加的一个功能,这意味着可能有充分的理由迁移到"Angular Approved"方法.

typescript angular-http angular-http-interceptors angular

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

Angular 5 Http Interceptor刷新JWT令牌

我已经实现了令牌保存,检索和我也有刷新调用的逻辑.问题是,当我在我的HttpInterceptor中拦截403时,同时进行的其他调用也会刷新令牌.在我的令牌刷新之前,我很想接听这些电话.创建我称之为"信号量"的请求.

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

private auth: AuthService;

constructor(private injector: Injector) {
}

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.auth = this.injector.get(AuthService);

    if(this.auth.isAuthenticated()){
        request = request.clone({
            setHeaders: {
                Accept: 'application/json',
                Authorization: `Bearer ${localStorage.getItem('access_token')}`
            }
        });
    } else {
        request = request.clone({
            setHeaders: {
                Accept: 'application/json'
            }
        });
    }

    return next.handle(request).catch(error => {
        if (error.status === 401) {
            console.log('refreshing token');

            // TODO: return Refresh Token here and hold other calls
        }

        return Observable.throw(error);
    });
}
Run Code Online (Sandbox Code Playgroud)

angular-http-interceptors angular angular5

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

如何在 Angular 4/5 上将延迟加载模块中的拦截器添加到应用程序拦截器数组中?

我有AppModuleLazyLoadedModule。我想要从每个模块组件中得到的是:

  1. 来自 AppModule 组件的请求使用LoggerInterceptorUrlInterceptor
  2. 来自 LazyLoadedModule 组件的请求使用LoggerInterceptorUrlInterceptor以及FilterInterceptor

应用程序模块.ts

@NgModule({
  bootstrap: [AppComponent],
  declarations: [
    AppComponent,
  ],
  imports: [
    CoreModule,
    HttpClientModule,
  ],
  providers: [
     {provide: HTTP_INTERCEPTORS,useClass: LoggerInterceptor,multi: true},
     { provide: HTTP_INTERCEPTORS, useClass: UrlInterceptor, multi: true }
  ],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

延迟加载.module.ts

@NgModule({
  declarations: [
    LazyLoadedComponent,
  ],
  providers: [
     { provide: HTTP_INTERCEPTORS, useClass: FilterInterceptor, multi: true }
  ],
})
export class LazyLoadedModule {}
Run Code Online (Sandbox Code Playgroud)

问题是,当 LazyLoadedModule 延迟加载时,FilterInterceptor …

javascript dependency-injection angular-http-interceptors angular2-services angular

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

HttpInterceptor中的注入服务未初始化

我试图将服务注入HttpInterceptor,这是简单的服务

import { Injectable } from '@angular/core';
@Injectable()
export class LoginLoadingService {
   constructor() { }
   public loaded: boolean;
   isLoaded() {
       if (this.loaded === undefined) {
             this.loaded = true;
       }
       return this.loaded;
  }    
}
Run Code Online (Sandbox Code Playgroud)

和拦截器

import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from 
'@angular/common/http';
import { Injectable, Inject } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { LoginLoadingService } from './loading.service';
import 'rxjs/add/operator/do';
@Injectable()
export class LoginLoadingInterceptor implements HttpInterceptor {
  constructor(public loginLoadingService: LoginLoadingService) { }
  intercept(req: HttpRequest<any>, next: HttpHandler): …
Run Code Online (Sandbox Code Playgroud)

angular-http-interceptors angular

6
推荐指数
2
解决办法
4310
查看次数

Angular HttpInterceptor:如何在多种条件下使用RxJS

这是AuthInterceptor:

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    constructor(private authService: AuthService) { }

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

        const Token = this.authService.getToken();

        if (!Token) {
            return next.handle(req);
        }
 
        // Refresh Token first
        if (Token.expiresRefreshToken && Number(Token.expiresRefreshToken) < Date.now()) {
            this.authService.refreshTokenRefresh(Token.tokenref)
            .subscribe((response) => {
                localStorage.setItem('tokenref', response.tokenref);
                localStorage.setItem('tokenrefexp', response.tokenrefexp);
            });
        }
        // Then next Access Token
        if (Token.expiresToken && Number(Token.expiresToken) < Date.now()) {
            this.authService.refreshToken(Token.tokenref)
            .subscribe((response) => {
                localStorage.setItem('token', response.token);
                localStorage.setItem('tokenexp', response.tokenexp);
            });
        }
        // Original request with updated custom …
Run Code Online (Sandbox Code Playgroud)

javascript rxjs typescript angular-http-interceptors angular

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

当 rxjs 重新抛出 http 错误响应时,自定义全局错误处理程序不会被命中

目标:为服务器错误和应用程序错误(用 Typescript 代码生成)提供一个全局错误处理程序。

如何:从同一工作区中的 lib 项目提供自定义 ErrorHandler。这是我的库结构:

@common/错误处理库

我有以下 http-interceptor (http-error.interceptor.ts)

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {

  constructor(@Inject(LOGGER_SERVICE) private logger: ILoggerService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req)
    .pipe(
        catchError( (error: HttpErrorResponse) => {
          console.log('error');

          return throwError(error);
        })
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

以下自定义全局错误处理程序(errors-handler.ts):

import { ErrorHandler, Injectable } from '@angular/core';

@Injectable()
export class ErrorsHandler implements ErrorHandler {

    handleError(error: any): void {
        console.log('hi!');
    }

}
Run Code Online (Sandbox Code Playgroud)

这是错误处理.module.ts

import { NgModule, ErrorHandler } from '@angular/core';
import { HTTP_INTERCEPTORS } from …
Run Code Online (Sandbox Code Playgroud)

error-handling typescript angular-http-interceptors zone.js angular

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

HTTP拦截器发送相同的请求两次

我正在使用 HTTP 拦截器来向请求添加身份验证令牌,但是当 http 客户端触发请求时,该请求会被拦截并发送两次

这是我的 HttpClient 调用

  searchProd(query: string, limit?: number): Observable<Product[]> {
    let _limit = limit || 5;
    return this.http.get<Product[]>(`${API_CONST.HOST}/${API_CONST.PRODUCT}?search=${query}&limit=${_limit}`);
  }
Run Code Online (Sandbox Code Playgroud)

这是我的 app.module.ts

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; 
import { TokenInterceptor } from './auth/token.interceptor';
....

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  providers: [
    ApiService,
    AuthGuardService,
    SettingsService,
    {
      provide : HTTP_INTERCEPTORS,
      useClass : TokenInterceptor,
      multi : true
    }
  ],
  entryComponents: [ ... ],
  bootstrap: [ ... ]
})

Run Code Online (Sandbox Code Playgroud)

这是我的 token.interceptor.ts

import { Injectable } …
Run Code Online (Sandbox Code Playgroud)

rxjs angular-http-interceptors angular angular-httpclient

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

当我使用 HttpInterceptor 添加标头时,它们会添加到lazyUpdate,而不是标头数组

我已经通过 Angular 中的 HttpInterceptor 添加了授权标头,但输出似乎不正确。根据添加标头后的 JSON 输出,这感觉太笨拙而无法正确。我是否错误地添加了标头,或者我访问它们是否错误?:

headers["lazyUpdate"].forEach(x=>{x.name=='Authorization'}).value
Run Code Online (Sandbox Code Playgroud)

目标是回归Bearer mystring

拦截器调用:

{"url":" https://myurl ","body:{}, "reportProgress":false, "withCredentials":false, "responseType":"json", "method":"POST", "headers" :{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"params":{"updates":null,"cloneFrom":null,"encoder":{},"map" :null},"urlWithParams":"myurl"}

token.interceptor.ts:13拦截器添加token:

{"url":"myurl", "body":{}, "reportProgress":false, "withCredentials":false, "responseType":"json", "method":"POST", "headers":{" NormalizedNames":{},"lazyUpdate":[ {"name":"Authorization","value":"Bearer mystring","op":"s"} ], "headers":{},"lazyInit": {"normalizedNames":{},"lazyUpdate":null,"headers":{}}},"params":{"updates":null,"cloneFrom":null,"encoder":{},"map" :{}},"urlWithParams":"myurl"}

我的 TokenInterceptor 类:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {   
    console.log('interceptor called: '+JSON.stringify(request))

    let r = request.clone({
      headers: request.headers.set('Authorization', `Bearer ${localStorage.getItem("id_token")}`)
    });
    console.log('interceptor added token: '+JSON.stringify(r))
    return next.handle(r);
  }
}
Run Code Online (Sandbox Code Playgroud)

http-headers angular-http-interceptors angular

6
推荐指数
0
解决办法
1025
查看次数