Angular2 处理来自组件中服务的响应

Angular2 handling response from service in component

我的服务中有一个功能如下:

   addObject(name: string, path: Array<google.maps.LatLngLiteral>, cycle: string, type: string, size: string) {
     let obj = new SurveyObjectModel(name, path, cycle, type, size);

     let body = JSON.stringify(obj);
     let headers = new Headers({ 'Content-Type': 'application/json; charset=utf-8', 'Authorization': 'Token ' + localStorage.getItem('auth_token') });
     let options = new RequestOptions({ headers: headers });
     console.log(body);
     console.log(headers);
     return this.http.post(this._surveyObjectURL, body, options)
     .map(this.extractData)
     .catch(this.handleError)
   }

目前我在我的组件中处理如下:

  createExhibitionSuveyObject(data: any){

    this.exhibitionSurveyObjectService.addObject(
      data.name, data.farmer_email, 
      data.farmer_name, data.size, data.path, data.cycle, data.object_type).subscribe(

      response => this.exhibitionSurveyObjects = response,
      error =>  this.errorMessage = <any>error

      ); 
  }

但是我想独立处理成功和失败(即成功时我想显示警报,失败时我想显示错误消息)。

就像在 angular 中一样,我们有:

// Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

我怎样才能做到这一点?

更新

createExhibitionSuveyObject(data: any){

    this.exhibitionSurveyObjectService.addObject(
      data.name, data.farmer_email, 
      data.farmer_name, data.size, data.path, data.cycle, data.object_type).subscribe(

      response => {this.exhibitionSurveyObjects = response; console.log("response")},
      error =>  {this.errorMessage = <any>error; console.log("error")}

      );  
  }

这就是我现在能够对成功和错误执行操作的方式,我只是不知道语法。

您可以内联执行,也可以使用 ExceptionHandler 对象来捕获全局 http 错误。

您的内联代码几乎已经到位了。这是一个例子:

 this.http.post(url, body, requestOptions).subscribe(
            data => {
                let j = data.json();
               console.log('here is the json!', j);
            },
            error => {
                alert('oh no');
            }
);

如果你想使用 ExceptionHandler,那么你需要这样的东西:

在你的bootstrap中:

import { ExceptionHandler } from '@angular/core';
import { CustomExceptionHandler } from './INSERT-PATH/custom-exception-handler';

也在你的 bootstrap:

...
provide(ExceptionHandler, { useClass: CustomExceptionHandler })
...

自定义异常-handler.ts:

import { ExceptionHandler, Injectable } from '@angular/core';
import { Response } from '@angular/http';

@Injectable()
export class CustomExceptionHandler {
    constructor() {
    }

    call(error, stackTrace = null, reason = null) {
        if (error instanceof Response) {
            alert('oh dear, an HTTP error occurred');
        } else { 
            alert('unhandled error');  
        }
    }
}

需要注意的重要一点是,在此示例中,如果未内联处理错误,CustomExceptionHandler 将触发。所以不要在 HTTP 调用中执行 error =>{} 位:)