HttpClient - AngularBuildUp/angular-microworkshops-authorization GitHub Wiki

New package on the "@angular/common/http".

Build on top of the XMLHttpRequest interface. Additional benefits include testability support, strong typing of the request and response objects, request and response interceptor support and better error handling via APIS based on Observables.

First install the HttpClientModule which provides it, in your AppModule.

import {HttpClientModule} from "@angular/common/http";

@NgModule({
	imports: [
		HttpClientModule
	]
})

Then you can inject HttpClient into your components and services.

Example

import "rxjs/add/operator/shareReplay";
import "rxjs/add/operator/do";

class AuthService {
	constructor(private http: HttpClient) {}
	
	signUp(email: string, password: string) {
		return this.post<User>("/api/signup", { email, password })
			.shareReplay()
			.do((user) => this.subject.next(user));
	}
}

The HttpClient returns an Observable<T>. I casually pass the URI for the API and the request body.

The .shareReplay() method is the resulting observable is still retryable but the result of the HTTP POST is being cached.

The .do method: We want to notify parts of the class (or application) that we got a value. Yes we return it, but let's say I want to notify a subject that the user is available. This is exactly what I am doing here.

signUp() {
	const val = this.form.value;
	
	if(val.email && val.password && val.password === val.passwordConfirm) {
		this.authService.signUp(val.email, val.password)
			.subscribe(
				() => console.log("User created successfully"),
				console.error
			)
	}
}

Errors

To handle errors, add an error handler to your subscribe call.

The err parameter of the callback is of type HttpErrorResponse and contains useful information on what went wrong. Two types of errors: If backend error, it gets returned as an error. If exception on client side or network error prevents the request from completing successfully, an actual Error will be thrown.

Example

.subscribe(
	data => {},
	(err: HttpErrorResponse) => {
		if(err.error instanceof Error) {
			// client side or network error occurred
		} else {
			// backend unsuccessful response.
		}
	}
);
⚠️ **GitHub.com Fallback** ⚠️