Angular πŸ‡ΊπŸ‡¦ - practical notes
1.63K subscribers
1.6K photos
1 file
532 links
Angular - practical notes

This group is for posting practical notes for Angular developers. Mostly all posts are for quick implementation https://t.me/angular_practical_notes (Commenting on posts only in ENG and UA langs here). Welcome!
Download Telegram
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
πŸ‘2
πŸ“„ How to Rewrite a Interceptor into a Functional Interceptor in Angular

#angular #interceptor

βœ… Article link: https://medium.com/@seanhaddock_60973/how-to-create-a-functional-interceptor-in-angular-c2302cc67a90
πŸ‘2
πŸ“„ Angular Interceptors: Authentication Interceptor

#angular #interceptor

An authentication interceptor is used to add authentication tokens to outgoing requests and handle authentication-related errors. This is essential for securing your application’s API requests.


import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
} from '@angular/common/http';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler) {
const authToken = 'your-auth-token';
const authRequest = request.clone({
headers: request.headers.set('Authorization', `Bearer ${authToken}`),
});
return next.handle(authRequest);
}
}
πŸ”₯2
πŸ“„ Angular Interceptors: Error Handling Interceptor

#angular #interceptor

An error handling interceptor can be used to centralize error handling for HTTP requests. It can capture HTTP errors, log them, and perform appropriate actions like displaying error messages.


import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpErrorResponse,
} from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler) {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
// Handle and log the error here
console.error('HTTP Error:', error);
// Optionally rethrow the error to propagate it
return throwError(error);
})
);
}
}
πŸ”₯2
πŸ“„ Angular Interceptors: Logging 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 Interceptors: Caching 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

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 Interceptors: Loading Indicator 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 Interceptors: Timeout 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 Interceptors: Base URL 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 Interceptors: Retry 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 Interceptors: Offline Mode 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 Interceptors: JWT Refresh Token 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

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);
})
);
}
}
πŸ“„ Angular Interceptors: Localization Interceptor

#angular #interceptor

A localization interceptor can be used to automatically include the user’s preferred language or locale in HTTP requests, ensuring that the server sends responses in the appropriate language.


import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
} from '@angular/common/http';
import { LocaleService } from './locale.service';

@Injectable()
export class LocalizationInterceptor implements HttpInterceptor {
constructor(private localeService: LocaleService) {}

intercept(
request: HttpRequest<unknown>,
next: HttpHandler
) {
const userLocale = this.localeService.getUserLocale();
const localizedRequest = request.clone({
setHeaders: {
'Accept-Language': userLocale,
},
});
return next.handle(localizedRequest);
}
}
πŸ”₯3
πŸ“„ Content Security Policy (CSP) Interceptor

#angular #interceptor

A CSP interceptor can be used to automatically add Content Security Policy headers to outgoing HTTP requests to improve security.


import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
} from '@angular/common/http';

@Injectable()
export class CspInterceptor implements HttpInterceptor {

intercept(
request: HttpRequest<any>,
next: HttpHandler
) {
const cspHeader = "default-src 'self'; script-src 'self' 'unsafe-inline'";
const cspRequest = request.clone({
setHeaders: {
'Content-Security-Policy': cspHeader,
},
});
return next.handle(cspRequest);
}
}
πŸ“„ Angular Interceptors: Compression Interceptor

#angular #interceptor

A compression interceptor can be used to automatically request compressed content (e.g., gzip) from the server, reducing the amount of data transferred over the network.


import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
} from '@angular/common/http';

@Injectable()
export class CompressionInterceptor implements HttpInterceptor {
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
) {
const compressedRequest = request.clone({
setHeaders: {
'Accept-Encoding': 'gzip, deflate'
},
});
return next.handle(compressedRequest);
}
}
❀️ 🀍 Global Error Handler β€” Angular

#angular #error #interceptor

⚠️ The example is for presentation purposes only and can be refactored.

βœ… Article link
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
πŸ‘1