Angular2中如何用Observable替代Promise处理API HTTP错误并仅返回成功响应
sendRequest to Observable with internal error handling Got it, let's turn your Promise implementation into an Observable-based one while keeping all error handling locked inside the api.service—so observers only get notified when the request succeeds, and errors stay hidden from them entirely.
Step-by-step Implementation
First, make sure you have the necessary RxJS operators imported: we'll need catchError to intercept errors, and EMPTY to return a "no-value" Observable after handling errors (so downstream observers don't get any error notifications).
Here's the full code for your sendRequest method and updated error handling:
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable, EMPTY } from 'rxjs'; import { catchError } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class ApiService { constructor( private http: HttpClient, private tokenService: TokenService, // Assume this is your existing token service private router: Router // Assume this is your Router instance ) {} sendRequest(method: string, url: string, data: any): Observable<any> { const token = this.tokenService.getToken(); // Fetch your auth token as before const headers = new HttpHeaders({ 'Accept': 'application/json, text/plain, */*', 'Authorization': `bearer ${token}`, 'Content-Type': 'application/json;charset=UTF-8' }); return this.http.request(method, url, { body: data, headers }) .pipe( catchError((error) => { this.handleError(error); // Return EMPTY to ensure no error or value is sent to observers return EMPTY; }) ); } private handleError(response: any): void { if (response.status === 401 || response.status === 403) { this.tokenService.deleteToken(); this.router.navigate(['login']); } // Add your other error handling logic here (e.g., show error popups, log details) console.error('Request failed:', response); } }
Key Details Explained
catchErrorOperator: This replaces the Promise's.catch()method. It intercepts any error emitted by the HTTP request Observable before it reaches the subscriber.- Returning
EMPTY: After handling the error inhandleError, we returnEMPTY—a special Observable that immediately completes without emitting any values. This ensures your component/subscriber never receives an error notification, and only gets data if the request succeeds. - Header Setup: We're using Angular's
HttpHeadersclass instead of a plain object, which is the recommended approach for consistent header management with HttpClient. - Private
handleError: Keeping error handling as a private method keeps your service clean, follows separation of concerns, and ensures error logic isn't exposed to external callers.
Why This Works
When the HTTP request succeeds, the Observable emits the response data to your subscriber as expected. If an error occurs:
catchErrorcatches the error immediately- Your
handleErrormethod runs (clears the token, navigates to login, shows user-facing alerts, etc.) EMPTYis returned, so the Observable completes silently—no error reaches the subscriber, and they only get notified on successful requests.
内容的提问来源于stack exchange,提问作者Vojtech

