如何使用ng2-resource-rest和typeScript处理Angular2中的400/500状态等休息调用错误?
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>;
}
答案 0 :(得分: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;
}
)
答案 1 :(得分: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