如果我有一个像
<video id="player1" class="video-js" #player>
<source [src]="videoUrl" type="video/mp4">
</video>
Run Code Online (Sandbox Code Playgroud)
它会向那个发送一个 get 请求videoUrl。该请求不会被角度拦截器拦截。是否有可能以某种方式拦截?
我希望如果任何 api 返回 401 错误响应,用户就会自动注销。为此,我拦截每个请求,一旦错误代码出现 401,我就会清除本地存储中的 jwt 令牌,并且身份验证防护会阻止但是在实现拦截器之后(这方面的示例非常少,并且文档中也没有提及),我无法命中任何 HTTP 请求。下面是我的代码。提前致谢。
import { Injectable, Injector } from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse} from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/throw'
import 'rxjs/add/operator/catch';
@Injectable()
export class ResponseInterceptor implements HttpInterceptor {
constructor() {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).do((event: HttpEvent<any>) => {
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
// do error handling here
console.log('and the error is ');
console.log(err)
}
});
} …Run Code Online (Sandbox Code Playgroud) 我已经构建了一个HttpInterceptor紧跟 Angular 文档中的那个。
但是,作为拦截器的一部分,我需要进行异步调用。我用代码的简化版本(但语义相同)创建了一个StackBlitz。
拦截器看起来像:
export class AuthInterceptor implements HttpInterceptor {
constructor(private session: SessionService, private config: ConfigurationService) {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
const apiRoot = this.config.apiUrl;
if (apiRoot && req.url.startsWith(apiRoot)) {
return this.addAuth(req).pipe(switchMap(x => next.handle(x)));
} else {
return next.handle(req);
}
}
private addAuth(original: HttpRequest<any>): Observable<HttpRequest<any>> {
return from(this.session.getToken()).pipe(
map(token => {
const req = original.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
return req;
})
);
}
}
Run Code Online (Sandbox Code Playgroud)
这很简单:
req.url.startsWith() …unit-testing angular-http-interceptors angular angular-unit-test
我在为 Angular 7 应用程序中的子模块注册 HttpInterceptor 时遇到问题。我的意图是只拦截和调整从子模块执行的请求。拦截器的代码如下。
import {Injectable} from "@angular/core";
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from "@angular/common/http";
import {AuthService} from "../services/auth.service";
import {from, Observable} from "rxjs";
import {switchMap} from "rxjs/operators";
@Injectable()
export class AuthInterceptor implements HttpInterceptor
{
constructor(private authService: AuthService){}
intercept(request: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>
{
return from(this.authService.get()).pipe
(
switchMap(authData =>
{
const headers = request.headers.set('Authorization', 'Bearer ' + authData.jwtAccessToken);
const requestClone = request.clone({headers});
return next.handle(requestClone);
})
);
}
}
Run Code Online (Sandbox Code Playgroud)
它在子模块之一中注册
import { NgModule } from '@angular/core';
import { …Run Code Online (Sandbox Code Playgroud) 我是 Angular 的新手,我正在尝试实现 api 调用,它在所有 api 的标头中发送令牌,所以我正在使用拦截器。
我无法在请求中设置标头。
jwt.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let currentUser = localStorage.getItem('useremail')
let currentUserToken = localStorage.getItem('token')
if (currentUser && currentUserToken) {
request = request.clone({
setHeaders: {
'Authorization': `${currentUserToken}`
}
});
}
// console.log("Request", request)
return next.handle(request);
}
}
Run Code Online (Sandbox Code Playgroud)
app.module.ts
import { BrowserModule …Run Code Online (Sandbox Code Playgroud) 我有一个 HTTP 拦截器,在每次请求之前,我检查访问令牌是否已过期,如果是,我从我的服务订阅 http.post 调用,然后订阅它,当我获得新的访问令牌时,我将调用下一个。像这样处理(请求):
this.auth.refreshAccessToken().subscribe((token: string) => {
this.auth.newAccessToken = token;
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`
}
});
return next.handle(request);
});
Run Code Online (Sandbox Code Playgroud)
问题是它正在抛出 TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
这让我觉得我在那里打错了 http.post 调用。
编辑 1:我还没有机会彻底测试这个,但到目前为止似乎一切正常。在返回整个地图之前我有一个 console.log 但它没有触发,但是,其他一切都有效,并且每次我获得新的访问令牌并且 DID 发生时,我都会在任何地方更新 currentUser/权限,因此出于所有意图和目的,它似乎工作,这是更新的代码:
mergeMap(token => {
this.auth.newAccessToken = token;
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`
}
});
return next.handle(request);
})
Run Code Online (Sandbox Code Playgroud) typescript angular-http-interceptors angular angular-observable angular-httpclient
有谁知道是否可以使用 AngularFire 库拦截对 firebase cloudstore 的请求?
我想实现一个功能,在从云存储中添加/更新/删除项目时,在角度拦截器中显示吐司消息
我正在使用 AngularFire 库和 AngularFirestore。
我的拦截器适用于其他 http 请求,但在仅使用 Angular 内置 HttpClient 库使用该库时则无法正常工作。我可以在网络控制台中看到在从 cloudfirestore 添加/更新/删除项目时发出了 xhr 请求。
如何拦截来自 AngularFirestore 库的请求?
我正在使用@angular/fire 5.1.2 和 angular 7.2
谢谢,贾尼
firebase angular-http-interceptors angular google-cloud-firestore
我正在开发一个 Angular 库,其中有一个提供HttpInterceptor. 主要思想是让这个拦截器在导入此身份验证模块的任何应用程序中自动工作,而无需对其进行任何额外的设置。
到目前为止我所拥有的是以下内容:
认证模块
@NgModule({
imports: [ConcreteAuthModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: BearerInterceptor,
multi: true
}
]
})
export class AuthenticationModule {
static forRoot(config: AuthConfig): ModuleWithProviders {
return {
ngModule: AuthenticationModule,
providers: [
{
provide: AUTH_CONFIG,
useValue: config
}
]
};
}
}
Run Code Online (Sandbox Code Playgroud)
具体验证模块
@NgModule({
imports: [ThirdPartyLibModule],
providers: [
{
provide: AuthenticationService,
useClass: ConcreteAuthService
}
]
})
export class ConcreteAuthModule { }
Run Code Online (Sandbox Code Playgroud)
承载拦截器
@Injectable()
export class BearerInterceptor implements HttpInterceptor {
constructor(private authService: AuthenticationService) { } …Run Code Online (Sandbox Code Playgroud) 在我的 Angular 8 项目中,我实现了最简单的方法:HttpInterceptor,只传递请求,而不执行任何操作
在我的 Angular 8 项目中,我实现了一个简单的方法HttpInterceptor,只需克隆原始请求并添加一个参数:
@Injectable()\nexport class RequestHeadersInterceptor implements HttpInterceptor {\n\n intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {\n // original code return next.handle(request) // pass-by request as-is\n\n return next.handle(request.clone({\n params: request.params.set(\'language\', \'en\') }\n ));\n }\n}\n\nRun Code Online (Sandbox Code Playgroud)\n\n在我的服务中,我有一个getFoos()方法可以进行 HTTP 调用,该调用将被以下内容拦截RequestHeadersInterceptor:
import { HttpClient } from \'@angular/common/http\';\nimport { Injectable } from \'@angular/core\';\nimport { finalize } from \'rxjs/operators\';\nimport { Foo } from \'.\';\n\n@Injectable({\n providedIn: \'root\'\n})\nexport class FooService {\n constructor(private …Run Code Online (Sandbox Code Playgroud) 我有一个HttpInterceptor,出于开发目的,我想打印发出请求的函数的堆栈跟踪:
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('Who has made this request?', new Error().stack);
return next.handle(request);
}
}
Run Code Online (Sandbox Code Playgroud)
控制台日志的输出为:
at HttpInterceptorService.intercept (:4200/main.js:1344) [angular]
at HttpInterceptorHandler.handle (:4200/vendor.js:30718) [angular]
at HttpXsrfInterceptor.intercept (:4200/vendor.js:31484) [angular]
at HttpInterceptorHandler.handle (:4200/vendor.js:30718) [angular]
at HttpInterceptingHandler.handle (:4200/vendor.js:31549) [angular]
at MergeMapSubscriber.project (:4200/vendor.js:30457) [angular]
at MergeMapSubscriber._tryNext (:4200/vendor.js:112207) [angular]
at MergeMapSubscriber._next (:4200/vendor.js:112197) …Run Code Online (Sandbox Code Playgroud) angular ×7
typescript ×3
javascript ×2
angular5 ×1
angular6 ×1
angular7 ×1
firebase ×1
rxjs ×1
unit-testing ×1
video ×1