我正在使用 http 拦截器来拦截应用程序中的每个 http 请求。但我发现循环依赖: $http <- APIInterceptor <- $http <- $templateRequest <- $compile
这是我的服务代码:
mPosServices.factory('mosServiceFactory', function ($http, $rootScope, $cookies, $q) {
return{
refresh_token: function () {
var refreshToken = $http({
method: "get",
url: "myservice/oauth/token?grant_type=refresh_token&client_id=restapp&client_secret=restapp&refresh_token=" + $cookies.get('refresh_token'),
})
return refreshToken;
}
});
mPosServices.service('APIInterceptor', ['mosServiceFactory','$cookies',function (mosServiceFactory,$cookies) {
var service = this;
service.request = function (config) {
if (!$cookies.get('access_token')) { //if access_token cookie does not exist
mosServiceFactory.refresh_token().then(function (response) {
var date = new Date();
date.setTime(date.getTime() + (response.data.expiresIn * 1000));
$cookies.remove('access_token');
$cookies.put('access_token', …Run Code Online (Sandbox Code Playgroud) 我有以下循环依赖:
$http
/ \
/ \
/ \
/ \
LoginManager------Interceptor
(service) (factory)
Run Code Online (Sandbox Code Playgroud)
这个循环依赖只在我添加了Interceptor的代码后才出现.
InterceptorLoginManager如果某个response被截获,将调用注销功能.
从我看到的,唯一的解决方案是将拦截器代码移动到
LoginManager服务中anonymous factory
有没有更好的方法?
我Http之前使用的是Angular 模块,并且该方法res.json()用于正常工作.我最近尝试过,HttpClient但res.json()似乎没有工作.只有使用res作品才能告诉我http客户端发生了什么变化.
return this.client.get('https://swapi.co/api/people/1/')
.map((res:Response) => {
return res.json(); // using maps to filter data returned form the http call this json dosn't work with http client
}).map(data => {
return data; // using maps of maps to filter data returned form the map
}).flatMap((jedi) => this.http.get(jedi['homeworld'])
.map(res => {
return res.json().name; // using flat maps to combine data returned from two observables into one
}).catch((error:any) => Observable.throw(error.json().error || 'Server …Run Code Online (Sandbox Code Playgroud) 我正在尝试更新Http到较新的HttpClient.
对于 JWT 刷新,我扩展了Http类并覆盖了request()方法(/sf/answers/3202568981/)。
现在我想对拦截器做同样的事情。
这是我现在拥有的拦截器:
export class JwtRefreshInterceptor implements HttpInterceptor {
public constructor(
private httpClient: HttpClient,
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).catch((error: HttpErrorResponse) => {
if (error.status === 401) {
return this.httpClient.post(environment.base_uri + 'auth/refresh', {}).flatMap((response) => {
// get token from response.
// put token in localstorage.
// add token to the request.
// Do the request again with the new token.
return next.handle(request); …Run Code Online (Sandbox Code Playgroud) 我使用 ngx-translator 进行本地化。当我尝试读取本地化存储在本地文件夹中的 json 文件时,我收到错误 HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http:/host.com/api/资产/i18n/en.json”,好的:假,...}。我认为问题出在我在应用程序中使用的拦截器中。
// app.module.ts
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, 'assets/i18n/', '.json');
}
Run Code Online (Sandbox Code Playgroud)
如何在此功能中禁用拦截器?我试图将标头设置为 X-Skip-Interceptor,但它没有帮助。
localization interceptor angular-http-interceptors ngx-translate angular
我正在尝试制作一个 jsonwebtoken 拦截器,但由于某种原因它根本没有设置标头。
对于我的提供者,我有
import { TokenInterceptorService } from './token-interceptor.service';
...
providers: [AuthService, AuthGuard, {
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptorService,
multi: true
}]
Run Code Online (Sandbox Code Playgroud)
因为我的TokenInterceptorService也很简单:
import { Injectable } from '@angular/core';
import { HttpInterceptor } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class TokenInterceptorService implements HttpInterceptor {
constructor() { }
intercept(req, next) {
let tokenizedReq = req.clone({
setHeader: {
Authorization: 'Bearer xx.yy.zz'
}
})
return next.handle(tokenizedReq);
}
}
Run Code Online (Sandbox Code Playgroud)
如果我记录tokenizedReq标题什么都没有。我一定是忽略了什么。
我正在尝试在我的 Angular 6 应用程序中实现延迟加载,我所有的 http 调用都是在FeatureModule(延迟加载)中进行的,但我仍然必须添加HttpClientModule我的AppModule而不是FeatureModule. 真的不明白为什么。另外,当我在我的 中添加拦截器时FeatureModule,它们没有拦截任何请求。我必须将它添加到AppModule唯一的(我猜,这是因为HttpClientModule在 中AppModule)。
我想明白为什么会这样??为什么我们不能HttpClientModule并且HTTP_INTERCEPTORS只在我没有打电话的地方FeatureModule而不是在AppModule那里http?
当 JWT 令牌过期时,Web 应用程序应显示一个alert或 模式弹出窗口,然后应重定向到登录页面。目前我正在使用烤面包机消息。
我的组件中有很多 api 调用。我收到许多烤面包机消息“令牌已过期”。我应该只显示一条消息并重定向到登录页面。告诉我你的好主意。我在互联网上有一些文章。但我无法清楚地了解这些事情。
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpResponse,
HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
import { ToastrManager } from 'ng6-toastr-notifications';
import { Injectable } from '@angular/core';
import { JwtDecoderService } from './jwt-decoder.service';
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor(public router: Router,
public toastr: ToastrManager,
private jwtDecoder: JwtDecoderService, ) {
}
intercept(request: HttpRequest<any>, …Run Code Online (Sandbox Code Playgroud) 我在 HttpInterceptor 的响应中缺少 http 标头。我可以得到一个正文,但不能得到标题。请参阅附加的输出和我的代码。
@Injectable()
export class ApiVersionInterceptor implements HttpInterceptor {
intercept(
req: import("@angular/common/http").HttpRequest<any>,
next: import("@angular/common/http").HttpHandler
): import("rxjs").Observable<import("@angular/common/http").HttpEvent<any>> {
return next.handle(req).pipe(
tap(httpEvent=>{
// Skip request
if(httpEvent.type === 0){
return;
}
console.log("response: ", httpEvent);
})
);
}
}
Run Code Online (Sandbox Code Playgroud)
我正在执行命令
ng g interceptor error
Run Code Online (Sandbox Code Playgroud)
其中 error 是拦截器的名称
但面临如下问题:
An unhandled exception occurred: Schematic "interceptor" not found in collection "@schematics/angular".
Run Code Online (Sandbox Code Playgroud)
我们是否必须先安装任何软件包?
angular ×8
angularjs ×2
angular-http ×1
angular7 ×1
angular8 ×1
http ×1
http-headers ×1
interceptor ×1
javascript ×1
jwt ×1
localization ×1
response ×1
typescript ×1