简体   繁体   English

Angular2处理组件中服务的响应

[英]Angular2 handling response from service in component

I have a function in my service as follows: 我在服务中具有以下功能:

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

Currently I am handling it in my component as follows: 目前,我正在组件中按以下方式处理它:

  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

      ); 
  }

However I want to handle success and failure independently (ie on success I want show an alert and on failure I want to show error message). 但是,我想独立处理成功和失败(即成功时我想显示警报,失败时我想显示错误消息)。

Like in angular we had: 就像在角度我们有:

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

How can I achieve this? 我该如何实现?

UPDATE UPDATE

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

      );  
  }

That's how I am now able to perform actions on success and error, I just didn't know the syntax. 这就是我现在能够对成功和错误执行操作的方式,只是我不知道语法。

You can either do it inline, or you can use the ExceptionHandler object for catching global http errors. 您可以内联完成此操作,也可以使用ExceptionHandler对象捕获全局http错误。

You're pretty much already there with your inline code. 您的内联代码已经差不多在那里了。 Here's an example: 这是一个例子:

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

If you want to use an ExceptionHandler, then you'll need something like this: 如果要使用ExceptionHandler,那么您将需要以下内容:

In your bootstrap: 在您的引导程序中:

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

Also in your bootstrap: 同样在您的引导程序中:

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

custom-exception-handler.ts: 自定义异常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');  
        }
    }
}

Important to note, in this example, CustomExceptionHandler will fire if the error isn't being handled inline. 请注意,在此示例中,如果未内联处理错误,则将触发CustomExceptionHandler。 So don't do the error =>{} bit in your HTTP call :) 因此,请勿在HTTP调用中error =>{}位:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM