0

如何使用 ng2-resource-rest 和 typeScript 处理 Angular2 中的 400/500 状态等休息调用错误?

注册组件.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
    };
}

员工服务.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>;

}
4

2 回答 2

0

实际上,您有Response对象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:我已经发布了新版本,它也被重命名为 ngx-resource

于 2017-04-05T15:45:04.120 回答
0

尝试这个。

 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;
     }
  )
于 2017-03-01T07:03:40.787 回答