Angular 7-rxjs-响应代码为422时无法获取响应数据
请求
Request URL: url
Request Method: POST
Status Code: 422 Unprocessable Entity
api_service.ts具有
validate(){
return this.http.post<any>(url).pipe(
map(res => res || []),
catchError(error => throwError(error.message || error))
);
}
同时调用api服务validateCard
this._apiService.validate().subscribe((res) => {
console.log(res)
}, (error) => {
console.log(error)
})
HttpInterceptor
return next.handle(request)
.pipe(tap(
(response: HttpEvent<any>) => {
return response
},
(error: HttpErrorResponse) => {
console.warn('ERROR Interceptor', error);
return error
},
() => {
console.log("completed successfully");
}
))
问题是它甚至没有控制台记录任何内容。并且在catchError(error)中未定义错误。
也许您可以为服务编写测试以单独测试行为。对我而言,此测试有效,并且在我的案例中,我可以捕捉到错误响应。
describe('DogService', () => {
let httpTestingController: HttpTestingController;
let service: DogService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [DogService],
imports: [HttpClientTestingModule]
});
httpTestingController = TestBed.get(HttpTestingController);
service = TestBed.get(DogService);
});
afterEach(() => {
httpTestingController.verify();
});
it('should throw 422 error with data', () => {
service.likeDoggo().subscribe(
data => console.log("SUCCESS"),
error => {
expect(error.status).toBe(422);
}
);
const mockedResponse = { status: 422, statusText: 'Bad Request' };
const data = {
errors: ['Invalid request parameters']
};
httpTestingController.expectOne('http://test.at/doggo').flush(data, mockedResponse);
});
});