angular2 + primeng错误回调

时间:2018-05-21 12:05:58

标签: angular primeng

我正在使用primeNG galleria来显示图片,问题是某些链接可能已经过期。我想以某种方式放回一个错误显示某种默认图像(如onError事件)。是否有一些无证的方法可以做到这一点?

1 个答案:

答案 0 :(得分:0)

当使用httpclient完成服务器请求时,它还提供了一种处理反应式扩展(rx)的可观察对象的方法。这些observable包含一个catch方法,您可以在其中处理错误。

我用它来捕获服务器的错误并在屏幕上显示errorinfo。也许你可以在那里写逻辑来显示默认图像或类似的东西,这里是代码。

import { Component, ViewChild, Input, OnInit, Injectable, Injector } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { URLSearchParams, QueryEncoder,Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/catch';
import {ICustomer  } from '../components/table/Customer'
import { NotificationsService } from './notification.service';
import { IClientmessage } from './clientmessage';
import { DatabaseServiceIsbusy } from './databaseserviceIsbusy.service';

@Injectable()
export class CustomerserviceService {
    constructor(private http: HttpClient,private httpold: Http, private notificationService: NotificationsService, private databaseservice: DatabaseServiceIsbusy) {       
    }

    private baseUrlTask = 'http://localhost:4584/customer'

    private httpOptions = {
        headers: new HttpHeaders({ 
          'Access-Control-Allow-Origin':'*',
          'Content-Type': 'application/json',
        })
      };

    public addCustomer(customer: ICustomer):Observable<IClientmessage>{
        return this.http.post<IClientmessage>(this.baseUrlTask, customer,this.httpOptions).catch(error =>this.handleError(error));;
    }   

    private handleError(error: HttpErrorResponse): Observable<any> {
        console.error(error.error);
         let errormessage:IClientmessage= error.error
        this.notificationService.notify(errormessage.severity, errormessage.summary,errormessage.detail);
        this.databaseservice.displayLoader(false);
        return Observable.throw(error.error || 'Server error');
    }