2017-07-19 76 views
3

我试图用一个简单的http获取休息api。当没有登记我的API响应错误500这样的:HttpInterceptors处理http错误角度4.3

{ "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

+0

你的API也返回状态码500吗?或者它返回一个200与所述错误? – LookForAngular

+0

它也返回状态码500. –

+0

你是什么意思,防止在浏览器中登录?这是你唯一的目的吗? – LookForAngular

回答

0

我真的不明白你的目标,但如果你需要处理所造成的AJAX错误叫你需要以可观察到的.onError功能反应

this.httpService.get(url) 
.subscribe(
    // onnext 
    () => [...], 
    // onError 
    (err) => [...] 
); 

然而,onerror的回调是作为终端事件处理,如果你想继续流,你应该使用.catch运算符

如果你在谈论angularjs拦截器,恐怕没有当前的解决方案,因为我知道。但是您可以轻松地在服务中实现这些功能。 大多数时间的错误解决方案是多种多样的,所以除非你在全公司范围内建立审计服务或加载栏,最好的方法是应用更​​具体的逻辑

+0

我把一些代码例子,使其更容易undestand。 –

0

你可以使用GlobalErrorHandler,它扩展了ErrorHandler和实施的HandleError()方法。它不应该把它扔到浏览器。