【发布时间】:2017-09-05 09:08:41
【问题描述】:
我正在尝试使用一个简单的 http get 来使用 rest 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, []);
});
}
【问题讨论】:
-
你的 api 是否也返回状态码 500?或者它返回一个带有上述错误的 200?
-
它也返回状态码 500。
-
阻止浏览器登录是什么意思?这是你唯一的目的吗?
-
@LookForAngular 我放了一些代码示例以便更容易理解。
-
角度无法阻止失败的 ajax 调用日志记录。这更像是一个镀铬问题而不是一个角度问题。 stackoverflow.com/questions/4500741/…
标签: angular angular-http-interceptors