π Angular Interceptors: Logging Interceptor
#angular #interceptor
#angular #interceptor
A logging interceptor can be used to log the details of HTTP requests and responses, which is helpful for debugging and monitoring.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpResponse,
} from '@angular/common/http';
import { tap } from 'rxjs/operators';
@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler) {
return next.handle(request).pipe(
tap((event) => {
if (event instanceof HttpResponse) {
console.log('HTTP Response:', event);
}
})
);
}
}π Angular Pipes: Reverse String Pipe
#angular #pipe
Usage in an Angular template:
#angular #pipe
This pipe reverses the characters of a string.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'reverseString' })
export class RSPipe implements PipeTransform {
transform(value: string): string {
if (!value) return value;
return value.split('').reverse().join('');
}
}Usage in an Angular template:
<p>{{ 'Angular' | reverseString }}</p>
<!-- Output: "ralugnA" -->π₯1
This media is not supported in your browser
VIEW IN TELEGRAM
π Resizable Columns in Angular Table
#angular #directive #ui_element
β Article link: https://levelup.gitconnected.com/how-to-create-resizable-columns-in-angular-scrollable-table-a-step-by-step-guide-5b8f766c1f60
π Code link: https://stackblitz.com/edit/angular-6x5egd?file=src%2Fapp%2Fdirectives%2Fcolumn-resize.directive.ts
#angular #directive #ui_element
β Article link: https://levelup.gitconnected.com/how-to-create-resizable-columns-in-angular-scrollable-table-a-step-by-step-guide-5b8f766c1f60
Please open Telegram to view this post
VIEW IN TELEGRAM
π1π₯1
π Angular Interceptors: Caching Interceptor
#angular #interceptor
#angular #interceptor
A caching interceptor can be used to implement client-side caching for HTTP responses, reducing the number of unnecessary network requests.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpResponse,
HttpHeaders,
} from '@angular/common/http';
import { tap } from 'rxjs/operators';
@Injectable()
export class CacheInterceptor implements HttpInterceptor {
private cache = new Map<string, HttpResponse<unknown>>();
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
) {
if (request.method !== 'GET') {
return next.handle(request);
}
const cachedResponse = this.cache.get(request.url);
if (cachedResponse) {
return of(cachedResponse);
}
return next.handle(request).pipe(
tap((event) => {
if (event instanceof HttpResponse) {
this.cache.set(request.url, event);
}
})
);
}
}π₯1
π Angular Interceptors: Headers Interceptor
#angular #interceptor
#angular #interceptor
A headers interceptor can be used to add custom headers to outgoing HTTP requests. This is often used to set headers like βContent-Typeβ or include API keys.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
} from '@angular/common/http';
@Injectable()
export class HeadersInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<unknown>, next: HttpHandler) {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'X-API-Key': 'your-api-key',
});
const headersRequest = request.clone({ headers });
return next.handle(headersRequest);
}
}π₯1
π Angular Pipes: Phone Number Formatter Pipe
#angular #pipe
Usage in an Angular template:
#angular #pipe
Formats a raw string of numbers into a well-structured phone number format (e.g., (555) 555β5555).
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'phoneNumberFormatter' })
export class PNFPipe implements PipeTransform {
transform(value: string): string {
if (!value || value.length !== 10) return value;
return `(${value.slice(0, 3)}) ${value.slice(3, 6)}-${value.slice(6)}`;
}
}Usage in an Angular template:
<p>{{ '1234567890' | phoneNumberFormatter }}</p>
<!-- Output: "(123) 456-7890" -->π₯1
π Angular Interceptors: Loading Indicator Interceptor
#angular #interceptor
#angular #interceptor
A loading indicator interceptor can be used to show and hide loading spinners or progress bars during HTTP requests, providing a better user experience.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
} from '@angular/common/http';
import { LoadingService } from './loading.service';
import { finalize } from 'rxjs/operators';
@Injectable()
export class LoadingInterceptor implements HttpInterceptor {
constructor(
private loadingService: LoadingService
) {}
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
) {
this.loadingService.showLoading();
return next.handle(request).pipe(
finalize(() => {
this.loadingService.hideLoading();
})
);
}
}π1π₯1
π Angular Pipes: File Size Pipe
#angular #pipe
Usage in an Angular template:
#angular #pipe
Converts a file size in bytes to a more human-readable format, such as KB, MB, or GB.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'fileSize' })
export class FileSizePipe implements PipeTransform {
transform(bytes: number): string {
if (isNaN(bytes) || bytes === 0) return '0 Bytes';
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(
Math.log(bytes) / Math.log(1024)
);
return `${parseFloat((bytes / Math.pow(1024, i)).toFixed(2))} ${sizes[i]}`;
}
}Usage in an Angular template:
<p>{{ 1024 | fileSize }}</p>
<!-- Output: "1 KB" -->π₯2
π Angular Interceptors: Timeout Interceptor
#angular #interceptor
#angular #interceptor
A timeout interceptor can be used to set a maximum timeout for HTTP requests. It can be useful to prevent long-running requests from blocking your application.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
} from '@angular/common/http';
import { throwError, timer, Observable } from 'rxjs';
import { catchError, timeout } from 'rxjs/operators';
@Injectable()
export class TimeoutInterceptor implements HttpInterceptor {
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
): Observable<any> {
const timeoutDuration = 10000; // 10 seconds
return next.handle(request).pipe(
timeout(timeoutDuration),
catchError((error) => {
if (error.name === 'TimeoutError') {
// Handle timeout error here
console.error(
'Request timed out:', request.url
);
return throwError('Request timed out');
}
return throwError(error);
})
);
}
}π Angular Custom Directives: Custom Validation Directive
#angular #directive
#angular #directive
A custom validation directive in Angular allows you to create your own custom validation logic for form controls. In this example, weβll create a custom directive to validate that a password contains both letters and numbers. If the password doesnβt meet this criteria, weβll mark the form control as invalid and display an error message. Hereβs how you can create this custom validation directive
<input
type="password"
name="password"
[(ngModel)]="user.password"
#password="ngModel"
appPasswordValidator="[A-Za-z]+[0-9]+"
required
/>
<div *ngIf="
password.invalid
&& (password.dirty || password.touched)
">
<div *ngIf="password | hasError :'required'">
Password is required.
</div>
<div *ngIf="password | hasError :'passwordPattern'">
Password must contain letters and numbers.
</div>
</div>
π Angular Interceptors: Base URL Interceptor
#angular #interceptor
#angular #interceptor
A base URL interceptor can be used to prepend a base URL to all HTTP requests, simplifying the configuration of API endpoints.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
} from '@angular/common/http';
@Injectable()
export class BaseUrlInterceptor implements HttpInterceptor {
private baseUrl = 'https://api.example.com';
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
) {
const apiRequest = request.clone({
url: `${this.baseUrl}${request.url}`,
});
return next.handle(apiRequest);
}
}π Angular Custom Directives: Autofocus Directive
#angular #directive
#angular #directive
In this example, we apply the appAutofocus directive to an input element. When the page loads, this input field will automatically receive focus, making it convenient for the user to start typing immediately.
<input
type="text"
placeholder="Auto-focused input"
appAutofocus
/>
import { Directive, ElementRef, AfterViewInit } from '@angular/core';
@Directive({
selector: '[appAutofocus]'
})
export class AutofocusDirective implements AfterViewInit {
constructor(private el: ElementRef) {}
ngAfterViewInit() {
this.el.nativeElement.focus();
}
}β€3
π Angular Interceptors: Retry Interceptor
#angular #interceptor
#angular #interceptor
A retry interceptor can be used to automatically retry failed HTTP requests, which can be helpful in handling intermittent network issues.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
} from '@angular/common/http';
import { retry } from 'rxjs/operators';
@Injectable()
export class RetryInterceptor implements HttpInterceptor {
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
) {
// Define the maximum number of retries
const maxRetries = 3;
return next.handle(request)
.pipe(retry(maxRetries));
}
}β€2
π Angular Custom Directives: Lazy Load Images Directive
#angular #directive
#angular #directive
Creating a custom directive in Angular for lazy-loading images can help improve the performance and user experience of your website by loading images only when they are visible on the screen. In this example, weβll create a custom directive named appLazyLoad to implement lazy loading for images.
<img
src="placeholder.jpg"
data-src="lazy-image.jpg"
alt="Lazy-loaded image"
appLazyLoad
/>
π2β€1
π Angular Interceptors: Offline Mode Interceptor
#angular #interceptor
#angular #interceptor
An offline mode interceptor can be used to detect when the userβs device is offline and handle HTTP requests accordingly, such as storing them for later or showing a friendly message.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpErrorResponse,
} from '@angular/common/http';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
export class OfflineModeInterceptor implements HttpInterceptor {
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
) {
if (!navigator.onLine) {
console.error(
'Device is offline. Request not sent:',
request.url
);
return throwError(
new HttpErrorResponse({
status: 0,
statusText: 'Offline'
})
);
}
return next.handle(request);
}
}β€1
π Angular Custom Directives: Drag-and-Drop Directive
#angular #directive
#angular #directive
Creating a custom directive in Angular for drag-and-drop functionality can enhance the user experience by allowing users to interact with elements on your page. In this example, weβll create a custom directive named appDraggable to enable drag-and-drop functionality for elements.
<div appDraggable>
Drag me around!
</div>
β€3
π Angular Interceptors: JWT Refresh Token Interceptor
#angular #interceptor
#angular #interceptor
A JWT refresh token interceptor can be used to automatically refresh expired JSON Web Tokens (JWTs) and seamlessly continue making authenticated requests.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpErrorResponse,
} from '@angular/common/http';
import { AuthService } from './auth.service';
import { catchError, switchMap } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable()
export class JwtRefreshInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {}
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
) {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
if (
error.status === 401
&& error.error
&& error.error.message === 'Token expired'
) {
return this.authService.refreshToken().pipe(
switchMap(() => {
// Retry the original
// request with the new token
const token = `Bearer ${
this.authService.getAccessToken()
}`;
const updatedRequest = request.clone({
setHeaders: { Authorization: token },
});
return next.handle(updatedRequest);
}),
catchError(() => {
// Refresh token failed;
// log out the user or
// handle the error
// For example, you can
// redirect to the login page
this.authService.logout();
const msg = 'Token refresh failed';
return throwError(msg);
})
);
}
return throwError(error);
})
);
}
}π8β€1
π Angular Interceptors: Request Timing Interceptor
#angular #interceptor
#angular #interceptor
A request timing interceptor can be used to measure and log the time taken for each HTTP request, helping you identify performance bottlenecks.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
} from '@angular/common/http';
import { tap } from 'rxjs/operators';
@Injectable()
export class RequestTimingInterceptor implements HttpInterceptor {
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
) {
const msg = `
Request to ${request.url} took ${duration}ms
`;
const startTime = Date.now();
return next.handle(request)
.pipe(
tap(() => {
const endTime = Date.now();
const duration = endTime - startTime;
console.log(msg);
})
);
}
}