Angular 5中HTTP请求用Observable的优势及HttpClient使用困惑咨询
Hey there! Let's break this down for you since you're just getting started with Angular 5 and those reactive concepts like Observables can feel a bit overwhelming at first.
First off, let's look at the POST method you wrote:
create(model: any, URI): Observable<Object> { return this.http.post(API_URL+URI, model) .pipe( catchError(this.handleError('create', model)) ); } private handleError<T> (operation = 'operation'...
This is a solid starting point! You're correctly using Angular's HttpClient.post() which returns an Observable, and you're leveraging the pipe() method to add error handling with catchError. Your generic handleError function is a great practice too—it lets you reuse error handling logic across all your HTTP methods, while keeping track of which operation failed and the data involved, which is super helpful for debugging.
Now, let's dive into why using Observables for HTTP requests in Angular 5 is such a good call:
- Cancelable requests: Unlike Promises, Observables let you cancel in-flight HTTP requests using
unsubscribe(). For example, if a user navigates away from a page before a request finishes, you can cancel it to avoid unnecessary network traffic and prevent memory leaks. Promises can't be canceled once they're initiated, which is a big limitation here. - Multi-value streams: Observables can emit multiple values over time. This is perfect for scenarios like Server-Sent Events (SSE) where the server pushes updates to the client continuously. Promises only resolve once, so they can't handle these ongoing data streams.
- Powerful operator toolkit: With RxJS operators (used via
pipe()), you can manipulate your HTTP response stream in all sorts of useful ways:- Use
map()to transform raw API responses into your application's model objects - Use
retry()to automatically retry failed requests - Use
tap()to run side effects like logging without modifying the stream
These operations are far easier to implement with Observables than with Promises, which would require extra code wrapping.
- Use
- Seamless Angular integration: Observables are deeply integrated with Angular's ecosystem. For example, the
AsyncPipe(| async) in templates automatically subscribes to Observables and cleans up subscriptions when the component is destroyed—no need to manually manage subscriptions and risk memory leaks. It also works great with features like route guards and reactive forms, which are built around reactive patterns. - Cold subscription behavior: Observables are "cold", meaning the HTTP request doesn't start until you call
subscribe()on the Observable. This gives you full control over when the request is initiated—like waiting for a user to click a submit button before firing off the POST request. Promises execute immediately when they're created, which is less flexible.
A couple of quick tips to refine your code further:
- Specify a more precise return type for your
createmethod instead ofObservable<Object>. If your API returns a specific model (like aUserorProduct), useObservable<User>—this gives you TypeScript's type checking benefits and makes your code more maintainable. - Make sure your
handleErrorfunction returns a valid Observable. A common implementation looks like this:
This ensures that even if a request fails, your application doesn't crash—instead, it gets a fallback value to work with.private handleError<T>(operation = 'operation', result?: T) { return (error: any): Observable<T> => { // Log the error (you could also send this to a logging service) console.error(`${operation} failed: ${error.message}`); // Return a safe default value to keep the app running return of(result as T); }; }
内容的提问来源于stack exchange,提问作者Harikrishnan

