目标:
我试图在每个 ajax 调用上显示一个加载图标。为此,我添加了一个 HTTP 拦截器,该拦截器在一个或多个请求正在进行时将变量设置为 true,在所有请求完成时将变量设置为 false。UI 会测试该值并显示是否显示加载程序,具体取决于。
问题:
每次 ajax 调用时,都会引发错误:
ExpressionChangedAfterItHasBeenCheckedError:
Expression has changed after it was checked.
Previous value: 'ngIf: [object Object]'. Current value: 'ngIf: true'.
Run Code Online (Sandbox Code Playgroud)
具有可重现错误的简化 Stakckblitz:
https://stackblitz.com/edit/angular-h4rpfb
代码:
应用程序组件.html:
<p *ngIf="loaderService.isLoading | async">
Loading!
</p>
<p *ngIf="!(loaderService.isLoading | async)">
Not Loading!
</p>
<button (click)="loadSomething()">Load Something</button>
{{matches|async}}
Run Code Online (Sandbox Code Playgroud)
应用程序组件.ts:
import { Component } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { LoaderService } from "./core";
import { Observable } from "rxjs";
@Component({
selector: "my-app", …Run Code Online (Sandbox Code Playgroud) 我正在构建一个 SPA,其中主页将包含多个组件。我希望每个组件都有一个加载微调器,没有覆盖层,仅显示在组件内。
我已经实现了ng-http-loader 6.0.1,但它创建了一个覆盖层,并且微调器显示在整个页面上。我没有找到任何选项可以强制它留在该特定组件内。
如果没有,最好的方法是什么?对微调器进行硬编码,当http请求返回结果时,用结果替换微调器?我认为必须有更好的方法来做到这一点。
http使用的示例调用@angular/common/http HttpClient:
private startHttpRequest = () => {
this.http.get('/TestUrl/')
.subscribe(res => {
console.log(res);
});
Run Code Online (Sandbox Code Playgroud)
}
我用来SignalR显示和更新结果
signalr angular-http-interceptors angular angular-httpclient
我已经授权将令牌headers直接放入。我现在如何从 Angular 4 获取这个令牌Http Interceptor?
不幸的是,以下都不console logs包含此标题:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
//const changedReq = req.clone({headers: req.headers.set('Authorization', 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbkB3cC5wbCIsImV4cCI6MTUxMDY2NDM0M30.0iBktdr4-1EzTi1iaQOOfguK7HGVJF7JYkB-AF3uZgJrmKnVESAyKkHoNRzum1Pq5xZ6GJaZC9cbZQ2umMSfLA')});
console.log('req', req);
return next.handle(req).do((event: HttpEvent<any>) => {
console.log('event', event);
if (event instanceof HttpResponse) {
// do stuff with response if you want
}
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
this.ehs.setService(err.status, err.error);
// redirect to login
}
});
}
Run Code Online (Sandbox Code Playgroud) authorization header interceptor angular-http-interceptors angular
我遵循这个例子:https://www.intertech.com/Blog/angular-4-tutorial-handling-refresh-token-with-new-httpinterceptor/
一切都很好,除了方法handle401Error.除非我添加subscribe了拦截器,否则它不会执行.我必须错过一些东西,即使试图遵循这个例子.
这是相关的代码:
零件:
ngOnInit() {
this.service.getData()
.subscribe((response: any) => {
this.message = `Worked with status = ${response.status}`;
},
error => this.message = `Failed with status = ${error.status}`);
}
Run Code Online (Sandbox Code Playgroud)
服务:
constructor(private http: HttpClient) {
this.currentToken = this.authTokenStale;
}
public authTokenStale: string = 'stale_auth_token';
public authTokenNew: string = 'new_auth_token';
public currentToken: string;
getData() {
return this.http.get<{status}>('https://private-4002d-testerrorresponses.apiary-mock.com/getDataError401');
}
getAuthToken() {
return this.currentToken;
}
refreshToken(): Observable<string> {
this.currentToken = this.authTokenNew;
return Observable.of(this.authTokenNew).delay(200);
}
Run Code Online (Sandbox Code Playgroud)
拦截器:
isRefreshingToken: boolean …Run Code Online (Sandbox Code Playgroud) 我创建了一个HttpInterceptor(Angular5),以便为每个xhr请求添加"withCredentials:true".但每次我调用任何http请求时,都会收到以下错误:
ERROR TypeError: this.interceptor.intercept is not a function
at HttpInterceptorHandler.handle (http.js:1777)
at HttpXsrfInterceptor.intercept (http.js:2470)
at HttpInterceptorHandler.handle (http.js:1777)
at MergeMapSubscriber.eval [as project] (http.js:1447)
at MergeMapSubscriber._tryNext (mergeMap.js:128)
at MergeMapSubscriber._next (mergeMap.js:118)
at MergeMapSubscriber.Subscriber.next (Subscriber.js:91)
at ScalarObservable._subscribe (ScalarObservable.js:51)
at ScalarObservable.Observable._trySubscribe (Observable.js:172)
at ScalarObservable.Observable.subscribe (Observable.js:160)
Run Code Online (Sandbox Code Playgroud)
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from "@angular/common/http";
import {Observable} from "rxjs/Observable";
import {Injectable} from "@angular/core";
@Injectable()
export class GeneralInterceptor implements HttpInterceptor{
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const cRequest = req.clone({
withCredentials: true
});
return next.handle(cRequest);
}
}Run Code Online (Sandbox Code Playgroud)
这是app.moudle.ts
@NgModule({ …Run Code Online (Sandbox Code Playgroud)嗨,我是angular 5的新手,并跟着一些博客写了HTTP拦截器.
export class AngularInterceptor implements HttpInterceptor {
public http404 = false;
constructor() { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log("intercepted request ... ");
// Clone the request to add the new header.
const httpReq = req.clone(
{
headers: req.headers.set("headerName", "headerValue")
}
);
console.log("Sending request with new header now ...");
//send the newly created request
return next.handle(httpReq)
.catch((error, caught) => {
//intercept the respons error and displace it to the console
console.log("Error Occurred");
if(error.status === 404)
this.http404 = true; …Run Code Online (Sandbox Code Playgroud) 在HttpClientModule中,是否有一种传递标头和参数来获取请求的方法。
import { HttpHeaders, HttpParams, HttpClient } from @angular/common/http';
const headers = { headers: new HttpHeaders({}) }
let params = new HttpParams({ });
get(url, {params}) // http client get with params
get(url, {headers}); //http client get with headers
Run Code Online (Sandbox Code Playgroud)
我想要类似requestoptions的内容,或者想要一种语法来使httpClient获得发送请求标头和参数。
当前使用搜索参数构建完整的url并发送标头。
http-get angular-http angular-http-interceptors angular angular-httpclient
要为我的每个请求添加拦截器标头,但它会给我以下错误.
未捕获错误:[$ injector:cdep]找到循环依赖项:$ http < - Auth < - httpRequestInterceptor < - $ http < - $ templateRequest < - $ route
app.js
var app= angular.module('myDemoApp',['ngRoute'])
app.factory('httpRequestInterceptor', ['Auth', function (Auth) {
return {
request: function (config) {
config.headers['x-access-token'] = Auth.getToken();
return config;
}
};
}]);
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpRequestInterceptor');
});
Run Code Online (Sandbox Code Playgroud)
验证服务
(function () {
'use strict';
myDemoApp.factory('Auth', ['$http', '$window', Auth]);
/******Auth function start*****/
function Auth($http, $window) {
var authFactory = {};
authFactory.setToken = setToken;
authFactory.getToken = getToken;
return authFactory;
/*setToken …Run Code Online (Sandbox Code Playgroud) 我创建了一个实现httpinterceptor的角度拦截器.它适用于http GET请求.但是没有POST请求.
我的拦截器代码如下.
import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders,HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
constructor() { console.log('enter constructor');
}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
console.log('entered interceptor')
const token = localStorage.getItem('sessiontoken') != null ? localStorage.getItem('sessiontoken') : 'notoken';
const authReq = req.clone({ headers: req.headers.set("Authorization", token) });
return next.handle(authReq);
}
}
Run Code Online (Sandbox Code Playgroud)
该模块添加了提供程序.
providers: [
{
provide: HTTP_INTERCEPTORS,
useValue: { disableClose: true, …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用拦截器来处理http错误并重试特殊的错误状态,在我的情况下为状态码502。
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
retryWhen(errors => {
return errors
.pipe(
mergeMap(error => (error.status === 502) ? throwError(error) : of(error)),
take(2)
)
})
)
}
Run Code Online (Sandbox Code Playgroud)
但是它不起作用,但是当我retry()以这种方式使用时,它就可以完美地工作
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
retry(2),
catchError((error: HttpErrorResponse) => {
return throwError(error);
})
)
}
Run Code Online (Sandbox Code Playgroud) angular ×7
angular5 ×2
rxjs ×2
angular-http ×1
angular6 ×1
angular8 ×1
angularjs ×1
header ×1
http-get ×1
interceptor ×1
javascript ×1
signalr ×1
typescript ×1