标签: angular-http-interceptors

AngularJS身份验证+ RESTful API

用于Auth /(重新)路由的Angular + RESTful客户端通信w/API

这已经在几个不同的问题中得到了解决,并且在一些不同的教程中,但我遇到的所有以前的资源并没有完全触及.

在坚果壳中,我需要

  • 通过POST登录http://client.foohttp://api.foo/login
  • 为提供logout路由的用户提供"登录"GUI /组件状态
  • 能够在用户注销/注销时"更新"UI. 这是最令人沮丧的
  • 保护我的路由以检查身份验证状态(如果需要)并相应地将用户重定向到登录页面

我的问题是

  • 每次我导航到不同的页面时,我都需要调用以api.foo/status确定用户是否已登录.(ATM我正在使用Express进行路由)这会导致打嗝,因为Angular会确定ng-show="user.is_authenticated"
  • 当我成功登录/注销时,我需要刷新页面(我不想这样做)以填充类似的东西{{user.first_name}},或者在注销的情况下,清空该值.
// Sample response from `/status` if successful 

{
   customer: {...},
   is_authenticated: true,
   authentication_timeout: 1376959033,
   ...
}
Run Code Online (Sandbox Code Playgroud)

我试过的

为什么我觉得我在失去理智

  • 似乎每个教程都依赖于一些数据库(许多Mongo,Couch,PHP + MySQL,无限广告)解决方案,并且没有一个完全依赖于与RESTful API的通信来持久登录状态.登录后,会发送其他POST/GET withCredentials:true,因此不是问题
  • 我找不到任何做Angular + REST + Auth的示例/教程/回购,没有后端语言.

我并不太自豪

不可否认,我是Angular的新手,如果我以荒谬的方式接近它,也不会感到惊讶; 如果有人建议替代方案,我会很激动 - 即使它是汤到坚果.

我的使用Express主要是因为我真的很喜欢- 我JadeStylus …

javascript restful-authentication node.js angularjs angular-http-interceptors

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

向Angular Application添加多个HTTP拦截器

如何向Angular 4应用程序添加多个独立的HTTP拦截器?

我尝试通过providers使用多个拦截器扩展数组来添加它们.但是只有最后一个实际执行,Interceptor1才会被忽略.

@NgModule({
  declarations: [ /* ... */ ],
  imports: [ /* ... */ HttpModule ],
  providers: [
    {
      provide: Http,
      useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) =>
        new Interceptor1(xhrBackend, requestOptions),
      deps: [XHRBackend, RequestOptions],
    },
    {
      provide: Http,
      useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) =>
        new Interceptor2(xhrBackend, requestOptions),
      deps: [XHRBackend, RequestOptions]
    },
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

我显然可以将它们组合成一个单独的Interceptor类,这应该可行.但是,我想避免这种情况,因为这些拦截器具有完全不同的目的(一个用于错误处理,一个用于显示加载指示符).

那么如何添加多个拦截器呢?

http interceptor angular-http-interceptors angular

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

如何使角度模块忽略核心模块中添加的http拦截器

我有一个带有HttpInterceptor的核心模块用于授权处理,我在AppModule中包含了这个模块,这样使用HttpClient的所有其他模块都使用这个拦截器.

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

如何使模块绕过默认拦截器?

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: components,
  providers: [CustomService],
  exports: components,
})
export class ModuleWithoutInterceptorModule { }
Run Code Online (Sandbox Code Playgroud)

angular-http-interceptors angular

43
推荐指数
4
解决办法
2万
查看次数

如何取消/取消订阅所有挂起的HTTP请求的角度4+

如何取消/中止所有挂起的HTTP请求的角度4+.

有一种unsubscribe方法可以取消HTTP请求,但是如何一次取消所有待处理的请求.

特别是路线变化时.

我做了一件事

ngOnDestroy() {
  this.subscription.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)

但如何在全球实现这一目标

有任何想法吗?

rxjs typescript angular-http-interceptors angular

30
推荐指数
5
解决办法
3万
查看次数

Angular 4 Http Interceptor:next.handle(...).do不是一个函数

我创建了这个HTTPInterceptor以便能够更好地处理http错误,它在我执行git pull并运行npm install之前运行良好.

这是我的代码:

import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable} from "rxjs";
import {ToasterService} from "angular2-toaster";

@Injectable()
export class GobaeInterceptor implements HttpInterceptor {
    constructor(private toasterService: ToasterService){
    }
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req)
            .do(event => {
                if (event instanceof HttpResponse) {
                    let response = event.body;
                    if(response.Error){
                        this.toasterService.pop('error', 'Error '+response.Code, response.Message);
                    }
                }
            });
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

TypeError:next.handle(...).do不是GobaeInterceptor.webpackJsonp中的函数.../../../../../src/app/services/gobae.interceptor.ts.GobaeInterceptor.拦截(gobae.interceptor.ts:12)在HttpInterceptorHandler.webpackJsonp .../../../common/@angular/common/http.es5.js.HttpInterceptorHandler.handle(

最近有什么可以影响我的代码的东西改变了吗?我现在可以做什么来"捕获"拦截器上的http响应?

angular-http-interceptors angular

28
推荐指数
3
解决办法
2万
查看次数

如何在拦截器中取消当前请求 - Angular 4

如您所知,可以在新版本的Angular 4中使用Interceptor.

在我的,我想在某些条件下取消拦截器中的请求.那有可能吗?或者我应该问的是,我应该采取哪种方式?

它也会好的!如果我找到一种方法来重写对请求的一些响应而不是取消它.

angular-http-interceptors angular

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

如何在测试中模拟Angular 4.3 httpClient的错误响应

我有一个下面 interceptor auth-interceptor.service.ts

import {Injectable, Injector} from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {Cookie} from './cookie.service';
import {Router} from '@angular/router';
import {UserService} from './user.service';
import {ToasterService} from '../toaster/toaster.service';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    constructor(private injector: Injector) {}

    private handleError(err: HttpErrorResponse): Observable<any> {
        let errorMsg;
        if (err.error instanceof Error) {
            // A client-side or network error occurred. Handle it accordingly.
            errorMsg = `An error occurred: ${err.error.message}`;
        } …
Run Code Online (Sandbox Code Playgroud)

jasmine typescript angular-http-interceptors angular angular-httpclient

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

Angular 6 - 为什么在生成版本中缺少Bearer Token?(在dev构建中正常工作)

我正在使用Angular 6和HTTP Interceptor配置为将承载令牌应用于传出请求.

  • 在dev build(ng serve)中,应用了令牌,一切正常. :-)

  • 在生成build(ng serve --prod)中,请求是在没有承载令牌的情况下发出的. :-(

在prod构建中,我通过在应用它们之后将标头转储到控制台来验证正在应用标头.

我不知道为什么他们被排除在http请求之外.

我的environment文件没有差异.

我还应该注意什么?

丢失不记名令牌

我该怎么做才能解决这个问题?

起初我认为这是我的本地环境和我的暂存环境之间的问题,但后来我尝试在ng serve --prod本地运行并看到相同的结果.

所有这一切,除了一个是生产构建和一个开发构建之外,一切都是相同的.

智威汤逊拦截:

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        // add authorization header with jwt token if available
        let currentUser = JSON.parse(localStorage.getItem('currentUser'));

        if (currentUser && currentUser.token) …
Run Code Online (Sandbox Code Playgroud)

angular-http-interceptors angular

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

如何在Angular 5 HttpInterceptor中添加多个头文件

我正在尝试学习如何使用HttpInterceptor为应用程序对API执行的每个HTTP请求添加几个标头.我有这个拦截器:

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

import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';

import { Observable } from 'rxjs/Observable';


@Injectable()
export class fwcAPIInterceptor implements HttpInterceptor {
  intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

  const authReq = req.clone({
    headers: req.headers.set('Content-Type', 'application/json')
  });

  console.log('Intercepted HTTP call', authReq);

  return next.handle(authReq);
}
}
Run Code Online (Sandbox Code Playgroud)

}

除了'Content-Type'标题之外,我还需要添加'Authorization',但我不知道怎么做(Angular HttpHeaders的文档只是方法列表,没有任何解释).

我该怎么做?谢谢!

angular-http-interceptors angular angular-httpclient

19
推荐指数
4
解决办法
3万
查看次数

在打电话给我的api之前如何减速/等待?

祝你圣诞快乐.
我的Angular 4应用程序不会等待.

我希望在我调用API之前放慢速度.
但我只是继续撞墙.

我在我的代码中使用了HttpInterceptor.
但是这些Observable只会爆炸.

不要太鄙视.
下面你会发现我的尝试.

export class ApiUrlInterceptor implements HttpInterceptor {

    constructor(private http: Http) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return Observable.create(observer => {
            setTimeout(() => {
                observer.next(true); //Not sure why I do this
                const start = Date.now();
                console.log(`Request for ${req.url}`);
                return next.handle(req).do(event => {
                    if (event.type == HttpEventType.Response) {
                        const elapsed = Date.now() - start;
                        console.log(`Request for ${req.urlWithParams} took ${elapsed} ms.`);
                    }
                });
            }, 1000);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

结果是调用了API.
但没有安装调用者的结果

我的Observable似乎陷入困境.
我运气不好


我很清楚这是Angular中的反模式"不要等待随机数",而是构建你的应用程序,这样你就不需要了.我的实际用例是, …

wait rxjs angular-http-interceptors angular angular-httpclient

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