面试题答案
一键面试- 实现步骤:
- 导入
HttpClientModule
和catchError
操作符。 - 在数据请求方法中,使用
pipe
操作符链式调用catchError
方法来捕获错误。 - 在
catchError
方法的回调函数中处理错误,例如显示错误信息给用户等。
- 导入
- 关键代码示例:
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) {}
getData() {
return this.http.get('/api/data').pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 404) {
console.error('404错误:资源未找到');
} else if (error.status === 500) {
console.error('500错误:服务器内部错误');
}
return throwError(error);
})
);
}
}
在组件中使用:
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private dataService: DataService) {}
ngOnInit() {
this.dataService.getData().subscribe(
data => {
console.log(data);
},
error => {
console.error('发生错误:', error);
}
);
}
}