标签: angular-http-interceptors

创建$ http拦截器作为独立模块时Angular中的依赖性错误

这是一个工作示例,说明我如何设置一个拦截器,为每个请求附加一个身份验证令牌(这或多或少来自https://docs.angularjs.org/api/ng/service/ $ http)

angular.module("app", [])
.config(function ($httpProvider) {
  $httpProvider.interceptors.push("authInterceptor");
})
.factory("authInterceptor", function ($q) {
  return {
  // interceptor configuration here
  }
})
Run Code Online (Sandbox Code Playgroud)

config和我的run块中有很多其他的东西,它们调用和启动来自不同角度模块的服务,所以我想稍微整理一下.但是我知道在config块中依赖注入有一些非常具体的规则,我不太明白,这些都阻止我authInterceptor在一个单独的模块中定义我的工厂.由于configrun块中的其他逻辑调用应用程序中的其他模块,因此声明拦截器在那里看起来不合适.

这就是我想要做的:

angular.module("services.authInterceptor", [])
.factory("authInterceptor", function ($q) {
  return {
  // interceptor configuration here
  }
});

angular.module("app", [
 "services.authInterceptor"
]).config(function ($httpProvider, authInterceptor) {
  $httpProvider.interceptors.push("authInterceptor");
});

// Error: Unknown provider authInterceptor.
Run Code Online (Sandbox Code Playgroud)

我尝试将它注入到run块中,但我想你不允许注入$httpProvider它:

angular.module("app", [
  "services.authInterceptor"
]).run(function ($httpProvider, authInterceptor) {
  $httpProvider.interceptors.push("authInterceptor");
});

// …
Run Code Online (Sandbox Code Playgroud)

javascript dependency-injection angularjs angularjs-module angular-http-interceptors

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

身份验证 - $ http的.then()成功回调调用而不是错误回调

这可能只是因为误解了如何在MEAN堆栈应用程序中进行最佳身份验证,或者我对promises和$ http .then()方法的工作方式缺乏了解,但每当我尝试使用不正确的凭据对我的后端节点服务器进行身份验证时,它就是调用$ http .then()方法的成功回调而不是错误回调.这是我的设置:

我正在使用jsonwebtokenexpress-jwt包,AngularJS拦截器添加请求的令牌并检查状态401 responseErrors,设置/删除的TokenService等JWT,以及用于处理登录,注销等的UserService.

从调试开始,这是正在发生的事情:

  1. 发出登录请求
  2. 服务器捕获请求,查找指定的用户,但无法在数据库中找到它们.使用JSON对象返回401错误,包括错误消息等.
  3. HttpInterceptor使用该responseError方法,正确地看到它是状态401,删除任何可能的现有令牌,重定向到/login屏幕和returns $q.reject(response).
  4. UserService.login()正确使用错误回调并执行return response.
  5. 问题 - 我的login.js .login()方法中的成功回调运行,而不是第二个错误回调.我有一种感觉这与本文中讨论的关于承诺链的内容有关,但我的专业知识在这里有其限制,我无法理解我接下来应该做什么来告诉链中的下一个回调前一个有错误...

这是我的设置:

表达:

authRoutes.js

authRoutes.post("/login", function (req, res) {

    User.findOne({username: req.body.username}, function (err, user) {
        if (err) res.status(500).send(err);
        if (!user) {
            res.status(401).send({success: false, message: "User with the provided username was not found"})
        } else if (user) {
            bcrypt.compare(req.body.password, user.password, function (err, match) {
                if …
Run Code Online (Sandbox Code Playgroud)

javascript authentication jwt angularjs angular-http-interceptors

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

Angular - 同一组件中的 ExpressionChangedAfterItHasBeenCheckedError

我有一个简单的Angular 5应用程序,它带有一个HttpInterceptor,它在发出请求时通知服务。组件可以订阅此服务以获取此信息。

此处有错误的完整示例 => https://stackblitz.com/edit/angular-5b86se

在我的AppComponent 中,当我的子组件 ( HelloComponent ) 中发出请求时,我想显示一个加载指示器。

import { Component } from '@angular/core';
import { LoadingIndicatorService } from './loading-indicator.service';

@Component({
  selector: 'my-app',
  template: `<div *ngIf="loading" style="color:red">pretend this is loading indicator</div>
<hello name="{{ name }}"></hello>`
})
export class AppComponent  {
  name = 'Angular 5';
   loading: boolean = false;

   constructor(private loadingIndicatorService: LoadingIndicatorService) { 

    loadingIndicatorService
      .onLoadingChanged
      .subscribe(isLoading => this.loading = isLoading);
  }
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

错误:ExpressionChangedAfterItHasBeenCheckedError:检查后表达式已更改。以前的值:'假'。当前值:“真”。

如果我是正确的,当子组件更改父组件中的值时会出现此错误。

但是我的子组件(HelloComponent)只执行 HttpGet 并且HttpInterceptor正在通过具有可观察的服务更改父组件( …

angular-http-interceptors angular

7
推荐指数
2
解决办法
6325
查看次数

Angular 5 HttpInterceptor错误处理,首先调用调用方的错误处理

我有一个全局的HttpInterceptor,带有一个处理HttpErrorResponse的catch块。但是我的要求是,当服务进行http调用并且还具有错误处理程序时,我希望该服务上的错误处理程序首先退出。如果此服务上没有错误处理程序,那么我希望全局HttpInterceptor错误处理程序对其进行处理。

示例代码:

Http拦截器:

@Injectable()
export class ErrorHttpInterceptor implements HttpInterceptor {

constructor(private notificationService: NotificationService) {}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req)
  .catch(
    error => {
      if (error instanceof HttpErrorResponse) {
        this.notificationService.error('Error', 'Error in handling Http request');
      }

      return Observable.empty<HttpEvent<any>>();
    }
  );
 }
}
Run Code Online (Sandbox Code Playgroud)

和服务电话:

updateUser(id, data) {
  return this.http
    .patch(`${API.userUrl}/${id}`,  {data: data})
    .subscribe(
      () => console.log('success'),
      (err) => this.notificationService.error('custom code to handle this')
     );
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,ErrorHttpInterceptor给出通知,然后userService错误处理也给出错误通知。

但是在我的用例中,我只希望底层订阅未处理错误时,ErrorHttpIntercetor才能处理错误。有没有办法做到这一点?

angular-http-interceptors angular angular-httpclient

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

无法实例化循环依赖!HTTP_INTERCEPTORS ("[ERROR -&gt;]"): 在 NgModule CoreModule 中

我正在使用以下依赖项:

包.json:

{
  "name": "myApp",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --base-href /myapp/",
    "build": "ng build",
    "build-stage": "ng build --environment=stage --aot --prod --vendor-chunk=false --common-chunk=false",
    "build-prod": "ng build --environment=prod --aot --prod --vendor-chunk=false --common-chunk=false",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.2.4",
    "@angular/common": "^4.2.4",
    "@angular/compiler": "^4.2.4",
    "@angular/core": "^4.2.4",
    "@angular/forms": "^4.2.4",
    "@angular/http": "^4.2.4",
    "@angular/platform-browser": "^4.2.4",
    "@angular/platform-browser-dynamic": "^4.2.4",
    "@angular/router": "^4.2.4",
    "@ngx-translate/core": "^7.2.2",
    "@ngx-translate/http-loader": "^1.1.0",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "jquery": "^3.2.1",
    "qrcode": …
Run Code Online (Sandbox Code Playgroud)

rxjs typescript angular-http-interceptors angular

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

如何跨模块创建HttpInterceptor?

我对HttpInterceptors 上 Angular 文档底部的使用说明很好奇,它指出:

要为整个应用程序使用相同的 HttpInterceptors 实例,请仅在 AppModule 中导入 HttpClientModule,并将拦截器添加到根应用程序注入器。如果跨不同模块多次导入 HttpClientModule(例如,在延迟加载模块中),则每次导入都会创建 HttpClientModule 的新副本,这会覆盖根模块中提供的拦截器。

我不明白该怎么做。如何获取根应用程序注入器并将我的延迟加载模块的 HttpInterceptor 添加到其中?

似乎How to import Angular HTTP拦截器仅适用于子模块也试图回答这个问题,但答案对我来说同样不清楚。

为什么这不起作用,以及如何正确添加第二个延迟加载拦截器?

应用程序模块

@NgModule({
  imports: [RouterModule.forRoot(routes)], // routes contains a lazy load module
  declarations: [AppComponent],
  bootstrap: [AppComponent],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptorService,
      multi: true,
    }
  ]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

延迟加载子模块

@NgModule({
  imports: [
    LazyRoutingModule
  ],
  declarations: [ChildComponent],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: CacheInterceptorService,
      multi: true,
    }
  ]
}) …
Run Code Online (Sandbox Code Playgroud)

angular-http-interceptors angular angular-httpclient

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

如何在 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
查看次数

当 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
查看次数

在 Angular Interceptors 中获取当前路线

我想知道是否有办法在 Angular 的 HttpInterceptor 中检索当前路由。我正在使用来自不同路线的相同拦截器,但我需要检查是否正在从特定路线使用拦截器。如果是这样,我想在执行之前向后端请求添加一个特定的标头。

似乎RouteRouterActivatedRouteActivatedRouteSnapshot对此不起作用。

我目前使用windows.location作为临时解决方案,但想知道在 HttpRequest 拦截器中执行此操作的正确方法是什么。

我目前的代码:

@Injectable()
export class APIClientInterceptor implements HttpInterceptor {
  constructor() {
  }

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

    // Check if the call is done from the embed route.
    if (currentLocation.includes('/embed/')) {

      // Get the hash ID.
      const sIndex = currentLocation.lastIndexOf('/') + 1;
      const sLength = currentLocation.length - sIndex;
      const embedHash = currentLocation.substr(sIndex, sLength);
      console.log(embedHash);

      // Add the header to tell the …
Run Code Online (Sandbox Code Playgroud)

interceptor angular-routing angular-http-interceptors angular angular-router

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