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

时间:2017-10-31 15:38:43

标签: javascript angular angular-services angular-httpclient

我是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');
  }
}

Server 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窗口。我可以或者应该使用一些不同的方法吗?

1 个答案:

答案 0 :(得分:1)

是的,有可能,这样做:

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);
          }
      );
    }