HttpInterceptors 处理 http 错误 angular 4.3
HttpInterceptors handling http errors angular 4.3
我正在尝试通过简单的 http get 来休息 api。当没有注册时,我的 api 响应错误 500,如下所示:
{ "errors": [ { "code": "500", "message": "no registers." } ]}
所以,我想知道如何编写一个拦截器来处理所有类型的 http 错误,以防止在浏览器的控制台记录错误。
我的app.module.ts
import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { sharedConfig } from './app.module.shared';
import 'rxjs/add/operator/toPromise';
import { NoopInterceptor } from "./app.interceptor";
@NgModule({
bootstrap: sharedConfig.bootstrap,
declarations: sharedConfig.declarations,
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
...sharedConfig.imports
],
providers: [
{ provide: 'ORIGIN_URL', useValue: location.origin },
{
provide: HTTP_INTERCEPTORS,
useClass: NoopInterceptor,
multi: true,
}
]
})
export class AppModule {
}
我的app.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import { HttpErrorResponse } from "@angular/common/http";
@Injectable()
export class NoopInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const started = Date.now();
return next.handle(req)
.do(event => {
debugger;
if (event instanceof HttpResponse) {
const elapsed = Date.now() - started;
console.log(`Request for ${req.urlWithParams} took ${elapsed} ms.`);
}
});
}
}
我的app.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Config } from "./app.constantes";
@Injectable()
export class AppService {
protected config: Config;
constructor(private http: HttpClient) {
this.config = new Config();
}
get(service: string, complementos?: any, parametros?: any) {
var complemento = complementos != null && complementos.length > 0 ? complementos.join('/') : '';
var url = this.config.SERVER + service + this.config.TOKEN + '/' + complemento;
return this.http.get(this.config.SERVER + service + this.config.TOKEN + '/' + complemento);
}
}
compra.component.ts 是我打电话的地方
consultaPeriodoCompra(mes: any): void {
var lista = null;
this.service.get(this.config.CONSULTA_ULTIMAS_COMPRAS, ['2', mes.anoMes])
.subscribe((response) => {
this.atualizaLista(mes, response['payload'].listaTransacao);
},
(err) => {
this.atualizaLista(mes, []);
});
}
that it's what i want to prevent
我不太明白你的目标,但如果你需要处理由 ajax 调用引起的错误,你需要对可观察到的 .onError 函数做出反应
this.httpService.get(url)
.subscribe(
// onnext
() => [...],
// onError
(err) => [...]
);
但是,onError 回调被视为终端事件,如果您想继续流,您应该使用 .catch 运算符
如果你说的是 angularjs 拦截器,据我所知恐怕目前没有解决方案。但是您可以轻松地在您的服务中实现此类功能。
大多数时候错误解决方案是多种多样的,所以除非你在应用程序范围内构建审计服务或加载条,否则最好的方法是应用更具体的逻辑
实际上不可能实现你想要的,只是浏览器的默认行为,见 jeff 的回复@angular's github:
您可以使用扩展 ErrorHandler
的 GlobalErrorHandler 并实现 handleError() 方法。那它不应该把它丢给浏览器。
我正在尝试通过简单的 http get 来休息 api。当没有注册时,我的 api 响应错误 500,如下所示:
{ "errors": [ { "code": "500", "message": "no registers." } ]}
所以,我想知道如何编写一个拦截器来处理所有类型的 http 错误,以防止在浏览器的控制台记录错误。
我的app.module.ts
import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { sharedConfig } from './app.module.shared';
import 'rxjs/add/operator/toPromise';
import { NoopInterceptor } from "./app.interceptor";
@NgModule({
bootstrap: sharedConfig.bootstrap,
declarations: sharedConfig.declarations,
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
...sharedConfig.imports
],
providers: [
{ provide: 'ORIGIN_URL', useValue: location.origin },
{
provide: HTTP_INTERCEPTORS,
useClass: NoopInterceptor,
multi: true,
}
]
})
export class AppModule {
}
我的app.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import { HttpErrorResponse } from "@angular/common/http";
@Injectable()
export class NoopInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const started = Date.now();
return next.handle(req)
.do(event => {
debugger;
if (event instanceof HttpResponse) {
const elapsed = Date.now() - started;
console.log(`Request for ${req.urlWithParams} took ${elapsed} ms.`);
}
});
}
}
我的app.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Config } from "./app.constantes";
@Injectable()
export class AppService {
protected config: Config;
constructor(private http: HttpClient) {
this.config = new Config();
}
get(service: string, complementos?: any, parametros?: any) {
var complemento = complementos != null && complementos.length > 0 ? complementos.join('/') : '';
var url = this.config.SERVER + service + this.config.TOKEN + '/' + complemento;
return this.http.get(this.config.SERVER + service + this.config.TOKEN + '/' + complemento);
}
}
compra.component.ts 是我打电话的地方
consultaPeriodoCompra(mes: any): void {
var lista = null;
this.service.get(this.config.CONSULTA_ULTIMAS_COMPRAS, ['2', mes.anoMes])
.subscribe((response) => {
this.atualizaLista(mes, response['payload'].listaTransacao);
},
(err) => {
this.atualizaLista(mes, []);
});
}
that it's what i want to prevent
我不太明白你的目标,但如果你需要处理由 ajax 调用引起的错误,你需要对可观察到的 .onError 函数做出反应
this.httpService.get(url)
.subscribe(
// onnext
() => [...],
// onError
(err) => [...]
);
但是,onError 回调被视为终端事件,如果您想继续流,您应该使用 .catch 运算符
如果你说的是 angularjs 拦截器,据我所知恐怕目前没有解决方案。但是您可以轻松地在您的服务中实现此类功能。 大多数时候错误解决方案是多种多样的,所以除非你在应用程序范围内构建审计服务或加载条,否则最好的方法是应用更具体的逻辑
实际上不可能实现你想要的,只是浏览器的默认行为,见 jeff 的回复@angular's github:
您可以使用扩展 ErrorHandler
的 GlobalErrorHandler 并实现 handleError() 方法。那它不应该把它丢给浏览器。