处理错误与http全局服务角度4.3,handleError,401,0等,拦截器,jwt,标头

sta*_*ave 4 jwt angular

我有一个http全球服务,它被称为所有服务; 所以我可以通过例子来管理; 错误,警报,变量等.

customers.service.ts

export class CustomersService {
  childUrl = environment.apiUrl + 'customers';

  constructor(
    private http: HttpClient,
    private globalService: GlobalService
   ) {


  }

  public get(childUrl)  {
    return this.globalService.get(this.childUrl)
      .catch((res: Response) => this.handleError(res));
  }
  ...
  private handleError(err) {
    return Observable.throw(err);
  }
}
Run Code Online (Sandbox Code Playgroud)

global.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders  } from '@angular/common/http';
import { environment } from '../../environments/environment';

@Injectable()
export class GlobalService {

  url: string,

  constructor(private http: HttpClient) {

    this.headers = new HttpHeaders()
      .set('Content-Type', 'application/json; charset=utf-8')
      .set('Accept', 'application/json');


  }

  public prepare ( vars ) {
    this.url = environment.apiUrl + vars.childUrl;
  }
  public get( childUrl)  {

    this.prepare ({childUrl} );

    return this.http.get(this.url, { headers: this.headers, observe: 'response'})
      .catch((res: Response) => this.handleError(res);
  }
  private handleError(err) {
    return Observable.throw(err);
  }

}
Run Code Online (Sandbox Code Playgroud)

客户-list.component

export class CustomersListComponent implements OnInit {

  public customers: Array <any>;

  constructor (private customersService: CustomersService ) { }

  ngOnInit() {
    this.get();
  }

  private get(): void {
    this.customerService
      .get()
      .subscribe((data) => {this.customers = data.data; console.log(data) },
        error => console.log(error),
        () => console.log('Get all Items complete'));
  }
}
Run Code Online (Sandbox Code Playgroud)

在角度4.3之前,我有可观察量,我可以捕获错误,并在组件中在子服务中的全局服务中抛出一个可观察对象.现在它不起作用,我不知道如何管理catch,并处理observables的错误

在新的角度指南中:https: //angular.io/guide/http#error-handling

只是以简单的方式管理错误,

http
  .get<ItemsResponse>('/api/items')
  .subscribe(
    data => {...},
    (err: HttpErrorResponse) => {
      if (err.error instanceof Error) {
        // A client-side or network error occurred. Handle it accordingly.
        console.log('An error occurred:', err.error.message);
      } else {
        // The backend returned an unsuccessful response code.
        // The response body may contain clues as to what went wrong,
        console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
      }
    }
  });
Run Code Online (Sandbox Code Playgroud)

现在管理这个的正确方法是什么?

Deb*_*ahK 6

仍然有可观,你基本上可以保留现有组件代码不变.您需要更改的是使用新服务的服务代码HttpClient.

这是我的新服务:

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';

import { IProduct } from './product';

@Injectable()
export class ProductService {
    private _productUrl = './api/products/products.json';

    constructor(private _http: HttpClient) { }

    getProducts(): Observable<IProduct[]> {
        return this._http.get<IProduct[]>(this._productUrl)
            .do(data => console.log('All: ' + JSON.stringify(data)))
            .catch(this.handleError);
    }

    private handleError(err: HttpErrorResponse) {
        // in a real world app, we may send the server to some remote logging infrastructure
        // instead of just logging it to the console
        let errorMessage = '';
        if (err.error instanceof Error) {
            // A client-side or network error occurred. Handle it accordingly.
            errorMessage = `An error occurred: ${err.error.message}`;
        } else {
            // The backend returned an unsuccessful response code.
            // The response body may contain clues as to what went wrong,
            errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
        }
        console.error(errorMessage);
        return Observable.throw(errorMessage);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的组件中的方法,它基本上没有变化:

ngOnInit(): void {
    this._productService.getProducts()
            .subscribe(products => this.products = products,
                error => this.errorMessage = <any>error);
}
Run Code Online (Sandbox Code Playgroud)