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
πŸ“„ 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 Custom Directives: Lazy Load Images 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

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

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

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 Custom Directives: Ellipsis Directive

#angular #directive

Creating a custom directive in Angular to add ellipsis to text that overflows its container can help improve the readability and aesthetics of your user interface. In this example, we’ll create a custom directive named `appEllipsis` to add an ellipsis to text that exceeds its container's width.


<div appEllipsis>
This is a long text that will be truncated with an ellipsis if it overflows its container.
</div>
πŸ“„ 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
πŸ“„ Angular Custom Directives: Click Outside Directive

#angular #directive

Creating a custom directive in Angular to handle clicking outside a specific element, like a dropdown or modal, can enhance the user experience by allowing you to close these elements when users interact with the rest of the page. In this example, we’ll create a custom directive named appClickOutside to close a dropdown when users click outside of it.


<div 
appClickOutside
(appClickOutside)="closeDropdown()"
>
<button (click)="toggleDropdown()">
Toggle Dropdown
</button>
<div
*ngIf="dropdownOpen"
class="dropdown"
>
Dropdown content
</div>
</div>


import { Directive, ElementRef, Output, EventEmitter, HostListener } from '@angular/core';

@Directive({
selector: '[clickOutside]'
})
export class ClickOutsideDirective {
@Output() clickOutside = new EventEmitter<void>();

constructor(private el: ElementRef) {}

@HostListener('document:click', ['$event'])
onClick(event: Event): void {
const element = this.el.nativeElement;
if (!element.contains(event.target)) {
this.appClickOutside.emit();
}
}
}
πŸ”₯2πŸ‘1
πŸ“„ 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 Custom Directives: Confirm Dialog Directive

#angular #directive

Creating a custom directive in Angular to implement a confirm dialog can help you standardize and simplify the process of confirming actions before executing them, such as deleting items or making irreversible changes. In this example, we’ll create a custom directive named appConfirmDialog to open a confirmation dialog before executing an action.


<button 
[appConfirmDialog]="'Are you sure you want to perform this action?'"
>Delete</button>
πŸ“„ 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);
}
}
πŸ“„ Angular Custom Directives: Infinite Scroll Directive

#angular #directive

Creating a custom directive in Angular for implementing infinite scrolling can significantly improve the user experience, especially when dealing with long lists of data. In this example, we’ll create a custom directive named appInfiniteScroll to load additional content as the user scrolls down a page.


<div
appInfiniteScroll
class="scrollable-content"
(scrolled)="loadMoreData()"
>
<!-- Your list of items -->
</div>


import { Directive, ElementRef, HostListener, Input, Output, EventEmitter } from '@angular/core';

@Directive({
selector: '[appInfiniteScroll]'
})
export class InfiniteScrollDirective {
@Input() scrollThreshold = 100;
@Output() scrolled = new EventEmitter<void>();

constructor(private el: ElementRef) {}

@HostListener('scroll', ['$event'])
onScroll(event: Event): void {
const {
scrollHeight,
scrollTop,
clientHeight
} = event.target as HTMLElement;
const atBottom = scrollHeight - scrollTop <= clientHeight + this.scrollThreshold;

if (atBottom) {
this.scrolled.emit();
}
}
}
πŸ‘1
Hello, friends!
As you can see, I'm a Ukrainian software engineer who tries to do volunteer fundraisers to support the Armed Forces of Ukraine. Sometimes it takes a lot of time and I am not able to maintain this channel for you. Please help me close these fundraisers because without the Ukrainian army there will be nothing Ukrainian. Thank you very much!

πŸ’΅ FOR Ukraine:
https://send.monobank.ua/jar/697qLyfKgT
5375 4114 1222 8582

🌎 FOR ALL DONATS:

πŸ’΅ SWIFT code: UNJSUAUKXXX

πŸ’΅ PayPal: luckystudydanit@gmail.com

My profile with reports after closing fundraiser :
https://www.facebook.com/volunt2erua/

also all reports in our πŸš€ channel:
https://t.me/toxicc_squad
Please open Telegram to view this post
VIEW IN TELEGRAM
πŸ‘6
πŸ€“ Memory Leaks in JavaScript

#js

In JavaScript, a memory leak occurs when a program reserves memory for objects or data that are no longer needed or referenced, preventing the JavaScript engine’s garbage collector from freeing up that memory. Over time, this can lead to performance issues, such as sluggishness and unresponsiveness in web applications.


βœ… Article link: https://medium.com/@stheodorejohn/memory-leaks-in-javascript-causes-solutions-and-best-practices-18d8faecc672
πŸ‘2