HTTP
1. Import it to the application module:
import { HttpClientModule } from '@angular/common/http'
imports: [
BrowserModule,
HttpClientModule
],
2. Inject HttpClient into your service:
constructor(private http: HttpClient) {
}
3. Use it:
public getUsers(): Observable<User[]> {
return this.http.get<User[]>(`${BASE_URL}`);
}
4. Call an API inside of your component:
this.usersService.getUsers().subscribe(
(response) => ...,
(error) => ...,
() => ...
)
Pass count and text fragment as a query params
return this.http.get<User[]>(`${BASE_URL}`, {
params: {textFragment, count}
});
Full get method description:
get(url: string, options?: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe?: 'events' | 'response' | 'body';
params?: HttpParams | {
[param: string]: string | string[];
};
reportProgress?: boolean;
responseType?: 'arraybuffer' | 'blob' | 'text' | 'json';
withCredentials?: boolean;
}): Observable<any>;
Create a new hero
return this.http.post<Hero>(`${BASE_URL}`, hero, httpOptions);
Full post method description:
post(url: string, body: any, options?: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe?: 'events' | 'response' | 'body';
params?: HttpParams | {
[param: string]: string | string[];
};
reportProgress?: boolean;
responseType?: 'arraybuffer' | 'blob' | 'text' | 'json';
withCredentials?: boolean;
}): Observable<any>
Handle error in the component:
public search(queryString: string): void {
this.usersWithParamsSubscription = this.usersService
.getUsersWithParams(queryString, this.countToLoad)
.subscribe(
(res: User[]) => {
this.users = res;
},
(error: HttpErrorResponse) => console.log(error)
)
}
Handle error in the service and retry:
public getUsersWithParams(textFragment: string, count: string): Observable<User[]> {
return this.http.get<User[]>(`${BASE_URL}`, { params: { textFragment, count } })
.pipe(
retry(4),
catchError(this.handleError)
);
}
Describe interceptor as a TypeScript class with @Injectable decorator:
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Clone the request and replace the original headers with
// cloned headers, updated with the authorization.
const authReq = req.clone({
headers: req.headers.set('Authorization', 'Bearer token')
});
// Pass the request to the next handler
return next.handle(authReq);
}
}
Provide your interceptor:
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },