我有一个http拦截器服务,该服务将在成功和失败时显示一条吐司消息,并且工作正常。
但是我想跳过此举杯以获取所有请求,因为每次打开页面时它都会显示成功举杯。
我只想在用户手动发出请求时显示
import { Jsonp } from '@angular/http';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from "@angular/core"
import { Observable } from "rxjs";
import { tap, catchError } from "rxjs/operators";
import { ToastrService } from 'ngx-toastr';
import { of } from 'rxjs/observable/of';
@Injectable()
export class AppHttpInterceptor implements HttpInterceptor {
constructor(public toasterService: ToastrService) { }
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
tap(evt => {
if (evt instanceof HttpResponse && evt.body && evt.body.success) {
// this.toasterService.success(evt.body.success.message, evt.body.success.title);
this.displayToast(evt.body)
}
}),
catchError((err: any) => {
if (err instanceof HttpErrorResponse) {
try {
// this.toasterService.error(err.error.message, err.error.title);
this.displayToast(err.error)
} catch (e) {
// this.toasterService.error('An error occurred', '');
this.displayToast(err.error)
}
//log error
}
return of(err);
}));
}
displayToast(response) {
let message = response.message;
if (response.code == 200) {
this.toasterService.success('success');
} else if (response.code == 201) {
this.toasterService.success(message, 'Created');
} else if (response.code == 400) {
this.toasterService.error(message, 'Bad Request');
} else if (response.code == 401) {
this.toasterService.warning(message, 'Unauthorized');
} else if (response.code == 403) {
this.toasterService.warning(message, 'Forbidden');
} else if (response.code == 404) {
this.toasterService.warning(message, 'Not Found');
} else if (response.code == 409) {
this.toasterService.error(message);
} else if (response.code == 411) {
this.toasterService.info(message, 'No Records');
} else if (response.code == 500) {
this.toasterService.error(message, 'Internal Server Error');
} else if (response.code == 503) {
this.toasterService.error(message, 'Service Unavailable');
}
}
}
答案 0 :(得分:0)
您可以通过req.method
尝试一下:
requestMethod = req.method
if(requestMethod != "GET" {
this.displayToast(err.error)
}