Angular 2 http服务错误处理

时间:2018-05-19 12:05:45

标签: angular angular-http

我是angular 2的新手,我正在使用外部系统进行http api调用。我想向用户显示api错误作为toster通知。但我无法在错误处理方法中使用toster服务器..

import { BadInput } from './../common/bad-input';
import { NotFoundError } from './../common/not-found-error';
import { AppError } from './../common/app-error';
import { Http, RequestOptions , Headers } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';
import { environment } from '../../environments/environment';
import { ToastrService } from 'ngx-toastr';

@Injectable()
export class DataService {

options: object;

constructor( private http: Http , private toastr: ToastrService ) { 
  let headers = new Headers();
  headers.append('Content-Type', 'application/json');
  headers.append('Authorization', 'Bearer '+localStorage.getItem('token'));
  this.options = new RequestOptions({ headers: headers });

}

getAll(url: string) {
  return this.http.get(environment.apiEndPoint+url,this.options)
    .map(response => response.json())
    .catch(this.handleError);
}
create(url: string,resource) {
  return this.http.post(environment.apiEndPoint+url, JSON.stringify(resource),this.options)
    .map(response => {
       this.toastr.success( 'Data Saved Successfully');
       return response.json(); 
     })
    .catch(this.handleError);
}

private handleError(error: Response) {
  if (error.status === 403){
    this.toastr.error( 'User Login Failed');
    return Observable.throw(new BadInput(error.json()));
  }
  if (error.status === 500){
    this.toastr.error( 'Internal Server Error');
    return Observable.throw(new BadInput(error.json()));
  }
  if (error.status === 422){
    this.toastr.error( 'Validation Failed');
    return Observable.throw(new BadInput(error.json()));
  }

  if (error.status === 404){
    this.toastr.error( 'Not found');
    return Observable.throw(new NotFoundError(error.json()));
  }

  this.toastr.error( 'Something went wrong. Please contact Administrator!');
  return Observable.throw(new AppError(error.json()));
}

}

托特人的积极回应(200)正常。如果http引发任何错误,我无法在UI中处理它。

1 个答案:

答案 0 :(得分:0)

与map函数相同,错误函数需要来自服务器的东西! 地图需要查询结果,.error()需要错误对象! 所以你可以这样做:

getAll(url: string) {
  return this.http.get(environment.apiEndPoint+url,this.options)
    .map(response => response.json())
    .catch(error => this.handleError(error));
}

希望它有所帮助!!!