面试题答案
一键面试关键代码片段
- 在服务中设置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; }) ); } }
- 在组件中处理请求、超时提示及重试逻辑
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(); } }
- 在组件模板中显示相关信息及按钮
<div *ngIf="isLoading">加载中...</div> <div *ngIf="error">{{error}}</div> <button *ngIf="error" (click)="retry()">重试</button> <div *ngIf="data"> <!-- 显示数据的代码 --> </div>
思路
- 服务层:
- 使用
HttpClient
发起HTTP请求。 - 通过
pipe
操作符,使用timeout
操作符设置5秒的超时时间。 - 使用
catchError
操作符捕获错误,当错误为TimeoutError
时,抛出自定义的“网络超时”错误。
- 使用
- 组件层:
- 在组件中调用服务的方法发起请求。
- 使用
catchError
捕获服务中抛出的错误,并将错误信息存储在组件的error
变量中显示给用户。 - 使用
finalize
操作符在请求结束(成功或失败)时,将isLoading
设置为false
,以停止加载提示。 - 提供
retry
方法,该方法调用fetchData
方法重新发起请求。
- 模板层:
- 根据
isLoading
变量显示加载提示。 - 根据
error
变量显示错误信息,并提供重试按钮,点击按钮调用retry
方法重新发起请求。 - 根据
data
变量显示请求成功返回的数据。
- 根据