0

How to handle rest call error like 400/500 status in Angular2 using ng2-resource-rest and typeScript?

register.component.ts

registerEmployees() {
    let regEmployee = this.empService.employeeRegister(this.register);
    regEmployee.$observable
        .subscribe(
        (data: any) = > {
        regEmployee = data;
    }
    ),
        (error: any) = > {
        // I also made a layer to parse errors
    };
}

employee.service.ts

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

import{ ResourceAction, ResourceMethod, ResourceParams } from 'ng2-resource-rest';
import{ RestClient } from './global/rest-client';

@Injectable()
@ResourceParams({
url: 'http://localhost:8080/api/v1'
})
export class EmployeeServiceService extends RestClient {

    @ResourceAction({
    method: RequestMethod.Post,
        path : '/employee'
    })
    employeeRegister: ResourceMethod<any, any>;

}
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Gourab Paul
  • 575
  • 7
  • 14

2 Answers2

0

Try this.

 http
  .get('Some Url')
  .map(res => {
   // If request fails, throw an Error that will be caught
    if(res.status < 200 || res.status >= 300) {
     throw new Error('This request has failed ' + res.status);
   } 
   // If everything went fine, return the response
   else {
     return res.json();
   }
 })
.subscribe(
    (data: any) => {
          regEmployee = data;
     }
  )
raj m
  • 1,863
  • 6
  • 21
  • 37
0

In fact you have Response object as error which you can use to handle the error

registerEmployees() {
    let regEmployee = this.empService.employeeRegister(this.register);
    regEmployee.$observable
        .subscribe(
           (data: any) = > {
             // it's not need to set data, data is already set to the object
             //regEmployee = data;
           },
           (error: Response) => {
           // I also made a layer to parse errors
             if (error.status === 400) {
               console.log('My error JSON', error.json());
               console.log('My error TEXT', error.text()); 
             }

           }
        );
}

PS: I have released new version and also it was renamed to ngx-resource

Roman
  • 79
  • 4