MST

星途 面试题库

面试题:Angular HTTP请求超时后如何优雅地处理并重新发起请求

假设在Angular应用中,一个HTTP请求设置了超时时间为5秒,当请求超时时,不仅要提示用户网络超时,还要在用户点击重试按钮后重新发起该请求,写出实现该功能的关键代码片段及思路。
23.3万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

关键代码片段

  1. 在服务中设置HTTP请求及超时逻辑
    import { Injectable } from '@angular/core';
    import { HttpClient, HttpErrorResponse } from '@angular/common/http';
    import { Observable, catchError, timeout } from 'rxjs';
    
    @Injectable({
      providedIn: 'root'
    })
    export class ApiService {
      constructor(private http: HttpClient) {}
    
      public getData(): Observable<any> {
        return this.http.get('/api/data')
         .pipe(
            timeout(5000),
            catchError((error: HttpErrorResponse) => {
              if (error.name === 'TimeoutError') {
                throw new Error('网络超时');
              }
              throw error;
            })
          );
      }
    }
    
  2. 在组件中处理请求、超时提示及重试逻辑
    import { Component } from '@angular/core';
    import { ApiService } from './api.service';
    import { catchError, finalize } from 'rxjs';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      data: any;
      isLoading = false;
      error: string | null = null;
    
      constructor(private apiService: ApiService) {}
    
      fetchData() {
        this.isLoading = true;
        this.error = null;
        this.apiService.getData()
         .pipe(
            catchError((err) => {
              this.error = err.message;
              throw err;
            }),
            finalize(() => this.isLoading = false)
          )
         .subscribe((response) => {
            this.data = response;
          });
      }
    
      retry() {
        this.fetchData();
      }
    }
    
  3. 在组件模板中显示相关信息及按钮
    <div *ngIf="isLoading">加载中...</div>
    <div *ngIf="error">{{error}}</div>
    <button *ngIf="error" (click)="retry()">重试</button>
    <div *ngIf="data">
      <!-- 显示数据的代码 -->
    </div>
    

思路

  1. 服务层
    • 使用HttpClient发起HTTP请求。
    • 通过pipe操作符,使用timeout操作符设置5秒的超时时间。
    • 使用catchError操作符捕获错误,当错误为TimeoutError时,抛出自定义的“网络超时”错误。
  2. 组件层
    • 在组件中调用服务的方法发起请求。
    • 使用catchError捕获服务中抛出的错误,并将错误信息存储在组件的error变量中显示给用户。
    • 使用finalize操作符在请求结束(成功或失败)时,将isLoading设置为false,以停止加载提示。
    • 提供retry方法,该方法调用fetchData方法重新发起请求。
  3. 模板层
    • 根据isLoading变量显示加载提示。
    • 根据error变量显示错误信息,并提供重试按钮,点击按钮调用retry方法重新发起请求。
    • 根据data变量显示请求成功返回的数据。