I have http interceptor.
import { Injectable, Inject } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse } from '@angular/common/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { tap } from "rxjs/operators";
import { ToastrService } from 'ngx-toastr';
import { NgxSpinnerService } from "ngx-spinner";
@Injectable()
export class AppHttpInterceptor implements HttpInterceptor {
constructor(
@Inject('API_URL') private baseUrl: string,
public router: Router,
public toasterService: ToastrService,
private spinner: NgxSpinnerService
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// API url
request = request.clone({ url: `${this.baseUrl}/${request.url}` });
// notifications
return next.handle(request).pipe(
tap(evt => {
this.spinner.show();
if (evt instanceof HttpResponse && evt.body && typeof evt.body.success != "undefined") {
if(evt.body.success) {
this.spinner.hide();
this.toasterService.success(evt.body.message);
} else {
this.spinner.hide();
this.toasterService.error(evt.body.message);
}
} else {
this.spinner.hide();
}
})
);
}
}
there i am showing with toastr messages that are coming from backend, and if success is true then i show green toastr if false then red toastr indicating that something is wrong. And everything is good when the response status sent from nodejs backend api hosted on azure cloud is 200 ( the default one ).
context.res = {
body: { success: false, message: `Please add title field` }
};
The problem is if i send response with status 400 for example
context.res = {
status: 400,
body: { success: false, message: `Please add title field` }
};
then somehow the condition in mu http interceptor
evt instanceof HttpResponse
is not executed. But i don't know why. Why status code 400 is not instance of HttpReponse ?
question from:
https://stackoverflow.com/questions/65949687/status-400-sent-from-backend-is-not-recognised-as-httpresponse-in-the-angular-in 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…