简体   繁体   中英

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

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.

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:

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:

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. So don't do the error =>{} bit in your HTTP call :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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