Angular 中的全局错误处理

来源:undefined 2025-01-20 02:18:48 1028

在 Angular 17 中,优雅地处理服务订阅期间的错误并更新 UI 状态(例如加载指示器),可以使用 RxJS 的 catchError 运算符和可观察对象的 subscribe 方法。 以下步骤详细说明了如何实现:

方法:

加载指示器: 在发起服务调用前,设置一个布尔变量 isLoading 为 true,显示加载指示器。 服务调用结束后(无论成功或失败),将 isLoading 设置回 false,隐藏加载指示器。

错误处理: 使用 catchError 运算符捕获服务调用过程中发生的错误。 catchError 接收一个处理错误的函数,该函数可以记录错误、显示错误消息(例如使用 Toastr 或其他通知库)或执行其他错误处理逻辑。

UI 更新: 根据服务调用的结果更新 UI。成功时显示数据,失败时显示错误信息或默认状态。

示例代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

import { Component } from @angular/core;

import { MyService } from ./my-service.service;

import { catchError, finalize } from rxjs/operators;

import { of, throwError } from rxjs;

import { ToastrService } from ngx-toastr;

@Component({

selector: app-my-component,

templateUrl: ./my-component.component.html

})

export class MyComponent {

isLoading = false;

data: any = null;

errorMessage: string = null;

constructor(private myService: MyService, private toastr: ToastrService) { }

getData() {

this.isLoading = true;

this.errorMessage = null; // Clear previous error message

this.myService.getData()

.pipe(

catchError(error => {

this.toastr.error(数据获取失败, 错误);

console.error(Error fetching data:, error);

this.errorMessage = 数据获取失败,请稍后再试;

return throwError(() => error); // Re-throw the error to be handled by the next pipe

}),

finalize(() => this.isLoading = false) // Ensure loading indicator is always hidden

)

.subscribe({

next: response => {

this.data = response;

this.toastr.success(数据获取成功!, 成功);

},

error: err => {

// Error already handled in catchError, but can add additional error handling here if needed.

}

});

}

}

登录后复制

关键点:

isLoading 标志: 用于控制加载指示器的显示和隐藏。 catchError 运算符: 用于捕获和处理错误,并返回一个可观察对象以避免中断数据流。 这里我们重新抛出错误,以便subscribe的error回调也能捕获到。 finalize 运算符: 确保无论服务调用成功或失败,isLoading 都会被设置为 false。 错误消息: errorMessage 变量用于显示用户友好的错误信息。 Toastr: 用于显示用户友好的成功和错误通知。 您可以根据需要替换为其他通知库。

此方法提供了一种健壮且用户友好的方式来处理 Angular 17 中的服务调用错误,并保持 UI 的响应性。 记住根据您的实际需求调整错误处理和 UI 更新逻辑。

以上就是Angular 中的全局错误处理的详细内容,更多请关注php中文网其它相关文章!

最新文章