无法从 HttpClient 获得响应
Cannot get response from HttpClient
我一直在尝试处理来自 API 的错误响应。
我想要得到的:
我实际得到的是:
我的service.ts:
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
import { map, catchError } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';
private url = environment.urlServer;
constructor( private httpClient: HttpClient ) { }
guardarUsuario( data: {nombre: string, correo: string, pass: string, descripcion: string }) {
return this.httpClient.post(`${ this.url }/usuario`, data).pipe(
catchError((res: HttpErrorResponse) => {
console.log(res);
return throwError(JSON.stringify(res));
})
);
}
我的component.ts:
this.coreService.guardarUsuario( data )
.subscribe( res => {
console.log('Successfull response: ', res);
}, err => {
console.log('Error response', err);
}
);
更新:
这是拦截器代码
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { ToastrService } from 'ngx-toastr';
@Injectable({
providedIn: 'root'
})
export class AuthInterceptorService implements HttpInterceptor {
constructor(
private toastr: ToastrService
) { }
intercept( req: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> {
const token: string = sessionStorage.getItem('token');
let request = req;
if ( token ) {
request = req.clone({
setHeaders: {
'Authorization': `Bearer ${ token }`,
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true'
}
});
}
return next.handle(request).pipe(
catchError((err) => {
if (err.status === 401) {
this.toastr.error(`Error: ${ err }`)
}
throw throwError( 'Auth error: ', err );
})
);
}
}
这是我第一次使用拦截器,拦截器也已经导入到 app.module
的提供程序中。
如何从我的订阅错误处理程序中的 API 响应中获取错误消息?
您使用的 throwError
是否正确,它似乎没有导入您的代码中,例如
import { throwError } from 'rxjs';
此外,您通常需要从 HttpErrorResponse
中提取消息,例如:
return throwError(res.error.message);
拦截器有一个错误:throw throwError(..)
应该是return throwError(...)
如果它对某人有任何用处,我将 interceptor
的 catchError
更改为:
catchError((err) => {
if (err.status === 401) {
this.toastr.error(`Error: ${ err }`)
}
throw throwError( 'Auth error: ', err );
})
至:
catchError((error: HttpErrorResponse) => {
let errorMsg = '';
if (error.error instanceof ErrorEvent) {
errorMsg = `Error ${ error.error.message}`;
} else {
errorMsg = `Error code: ${error.status}, Message: ${error.message}`
}
return throwError(errorMsg);
})
并且 httpRequest
到:
guardarUsuario( data: {nombre: string, correo: string, pass: string, descripcion: string }) {
return this.httpClient.post(`${ this.url }/usuario`, data);
我一直在尝试处理来自 API 的错误响应。
我想要得到的:
我实际得到的是:
我的service.ts:
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
import { map, catchError } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';
private url = environment.urlServer;
constructor( private httpClient: HttpClient ) { }
guardarUsuario( data: {nombre: string, correo: string, pass: string, descripcion: string }) {
return this.httpClient.post(`${ this.url }/usuario`, data).pipe(
catchError((res: HttpErrorResponse) => {
console.log(res);
return throwError(JSON.stringify(res));
})
);
}
我的component.ts:
this.coreService.guardarUsuario( data )
.subscribe( res => {
console.log('Successfull response: ', res);
}, err => {
console.log('Error response', err);
}
);
更新: 这是拦截器代码
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { ToastrService } from 'ngx-toastr';
@Injectable({
providedIn: 'root'
})
export class AuthInterceptorService implements HttpInterceptor {
constructor(
private toastr: ToastrService
) { }
intercept( req: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> {
const token: string = sessionStorage.getItem('token');
let request = req;
if ( token ) {
request = req.clone({
setHeaders: {
'Authorization': `Bearer ${ token }`,
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true'
}
});
}
return next.handle(request).pipe(
catchError((err) => {
if (err.status === 401) {
this.toastr.error(`Error: ${ err }`)
}
throw throwError( 'Auth error: ', err );
})
);
}
}
这是我第一次使用拦截器,拦截器也已经导入到 app.module
的提供程序中。
如何从我的订阅错误处理程序中的 API 响应中获取错误消息?
您使用的 throwError
是否正确,它似乎没有导入您的代码中,例如
import { throwError } from 'rxjs';
此外,您通常需要从 HttpErrorResponse
中提取消息,例如:
return throwError(res.error.message);
拦截器有一个错误:throw throwError(..)
应该是return throwError(...)
如果它对某人有任何用处,我将 interceptor
的 catchError
更改为:
catchError((err) => {
if (err.status === 401) {
this.toastr.error(`Error: ${ err }`)
}
throw throwError( 'Auth error: ', err );
})
至:
catchError((error: HttpErrorResponse) => {
let errorMsg = '';
if (error.error instanceof ErrorEvent) {
errorMsg = `Error ${ error.error.message}`;
} else {
errorMsg = `Error code: ${error.status}, Message: ${error.message}`
}
return throwError(errorMsg);
})
并且 httpRequest
到:
guardarUsuario( data: {nombre: string, correo: string, pass: string, descripcion: string }) {
return this.httpClient.post(`${ this.url }/usuario`, data);