如何有一个页面重定向在API调用400错误的请求? 在角(How to have a page

2019-09-28 10:01发布

我想添加页面重定向到当我从一个API调用400错误的请求。 我会在哪里做? 在服务或component.ts:到目前为止我的代码是:

Service.ts

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

Component.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;
    })
  }

Answer 1:

您可以从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 },
  ],


Answer 2:

Alternatively, you may handle it on your component. This is because the .subscribe() method accepts 3 arguments/methods.

onNext- An Observable calls this method whenever the Observable emits an item. This method takes as a parameter the item emitted by the Observable.

onError - An Observable calls this method to indicate that it has failed to generate the expected data or has encountered some other error. This stops the Observable and it will not make further calls to onNext or onCompleted. The onError method takes as its parameter an indication of what caused the error (sometimes an object like an Exception or Throwable, other times a simple string, depending on the implementation).

onCompleted - An Observable calls this method after it has called onNext for the final time, if it has not encountered any errors.

Knowing that, we can redirect our users on the onError callback

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;
    }, error => {
      this.router.navigate(['/handle']);
    })


文章来源: How to have a page redirect on a 400 bad request in api call? In Angular
标签: angular