Angular2处理组件中服务的响应

时间:2016-07-24 10:40:46

标签: angularjs angular ionic2

我的服务功能如下:

   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

      ); 
  }

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

就像角度一样:

// 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")}

      );  
  }

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

1 个答案:

答案 0 :(得分:2)

您可以内联,也可以使用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,那么你需要这样的东西:

在你的引导程序中:

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

同样在你的引导程序中:

...
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 =>{}位:)