首页 > 解决方案 > 如何在 api 调用中对 400 错误请求进行页面重定向?在角

问题描述

当我从 api 调用收到 400 错误请求时,我正在尝试添加页面重定向。我会在哪里做这个?在服务或component.ts中:到目前为止我的代码是:

服务.ts

  getIncidents(customerId): Observable<any> {
   return this.http.get<any>(this.incidentApiUrl + "?customer_id=" + customerId)
      .pipe(
        catchError(this.handleError)
      );
  }

组件.ts

private getIncidents() {
    this.service.getIncidents(this.customer_id).subscribe((data) => {
      this.loading = true;
      console.log('Data' + data);
      this.showTable = this.data = data.result;
      this.loading = false;
      console.log('Result - ', data);
      console.log('data is received');
      this.errorApi = data.result == null || data.result === 0 || data.result.length === 0;
    })
  }

标签: angular

解决方案


您可以从 HttpInterceptor 创建 ErrorInterceptor

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';



@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    constructor(private router: Router) {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            if (err.status === 400) {
                // redirect to some page
                 this.router.navigate(['/somepage']);
            }
            const error = err.error || err.statusText;
            return throwError(error);
        }))
    }
}

并在模块的提供者中添加相同的内容

  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
  ],

推荐阅读