1

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 (i.e. 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.

4
  • Where do you want to handle it independently? In addObject or in createExhibitionSuveyObject()? Commented Jul 24, 2016 at 10:44
  • Wherever it is appropriate, I guess handling it in service makes more sense, right? Commented Jul 24, 2016 at 10:48
  • "Wherever it is appropriate" is your call. createExhibitionSuveyObject is already handling it independently. .catch(this.handleError) might interfere though. Commented Jul 24, 2016 at 10:50
  • Yes I got it what you mean! thanks. I didn't know the syntax. Commented Jul 24, 2016 at 11:01

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.