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

标签 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() 这样的方法,它将使用指定应使用哪个 API 方法的参数来调用 get 方法。

我还有一个名为 general.component.ts 的组件,其中注入(inject)了 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
      }
    );
  }

}

将会有更多组件,例如将使用 api.servicegeneral.component。现在我陷入困境,因为如果 api.service 中发生错误,我需要在所有使用 api.service 的组件中弹出 UI 窗口。是否可能或者我应该使用一些不同的方法?

最佳答案

是的,这是可能的,这样做:

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

关于javascript - Angular 2 API 服务显示错误 UI 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47039255/

相关文章:

angular - 在 tsconfig.json 上使用路径无法使用 Angular 解析

javascript - 可观察的http服务

javascript - 如果通过另一个变量检查​​空/未定义,流类型细化不起作用

javascript - 想要将文本发布到 Tumblr

Angular 如何在服务中使用 Websocket?

javascript - AngularJS 更新服务变量不起作用

javascript - 在 ng-click 上从工厂方法调用模态窗口

javascript - 如何使用 rotator.js 触发 jquery 加载器

javascript - 如何使用 jQuery 验证动态添加的字段并阻止表单提交?

Angular - 绑定(bind)公共(public)/私有(private)属性