Angular 2 API 服务显示错误 UI 消息

Angular 2 API service to display error UI message

我是 Angular 2 的新手,如果问题很愚蠢,请原谅。

我必须从服务器获取数据并将其显示在组件中。服务器有一些 API 方法,所以我创建了 api.service.ts ,如下所示:

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

const protocol = 'http';
const domain = 'mydomain.ng';
const port = ':4200';

@Injectable()
export class ApiService {

  constructor(private http: HttpClient) { }

  buildQuery(apiMethod: string) {
    return `${protocol}://${domain}${port}/${apiMethod}`;
  }

  get(apiMethod: string): Observable<Response> {

    const query = this.buildQuery(apiMethod);

    return this.http.get<Response>(query)
    .map(
      resp => {
        if (resp.ok) {
          return resp;
        } else { // Server returned an error
          // here I need to show UI error in the component
        }
      }
    )
    .catch( // Error is on the client side
      err => {
        // here I need to show UI error in the component
      }
    );
  }

  getGeneralReport(): Observable<Response> {
    return this.get('generalReport');
  }
}

服务器API有很多方法,所以get()方法是为了执行实际请求和处理常见错误而设计的。然后我将有像 getGeneralReport() 这样的方法,它会调用 get 方法,参数指定应该使用哪个 API 方法。

我还有一个名为 general.component.ts 的组件,其中注入了 api.service

import { Component, OnInit } from '@angular/core';
import { ApiService } from '../../shared/api/api.service';

@Component({
  selector: 'app-general',
  templateUrl: './general.component.html',
  styleUrls: ['./general.component.scss']
})
export class GeneralComponent implements OnInit {

  generalInfo: Response;

  constructor(private apiService: ApiService) { }

  ngOnInit() {
    this.apiService.getGeneralReport().subscribe(
      data => {
        this.generalInfo = data;
        // Display the received data
      }
    );
  }

}

将会有更多组件,例如 general.component,它们将使用 api.service。现在我卡住了,因为如果api.service中发生错误,我需要在所有使用api.service的组件中弹出UI window。有可能还是我应该使用一些不同的方法?

是的,可以这样做:

this.apiService.getGeneralReport().subscribe(
  data => {
    this.generalInfo = data;
    // Display the received data
  }, 
   err => {
      // yourPopupmethod(err)
   }
);

并且在服务中抛出错误。因此,通过添加 HandleError 方法更新您的服务:

handleError(error: Response | any) {
     return Observable.throw(new Error(error.status))
}

  get(apiMethod: string): Observable<Response> {

    const query = this.buildQuery(apiMethod);

    return this.http.get<Response>(query)
       .map(
           resp => {
              if (resp.ok) {
                 return resp;
              } else { // Server returned an error
                 this.handleError(resp);
                }
           }
         )
       .catch(
          err => {
             this.handleError(err);
          }
      );
    }