0% found this document useful (0 votes)
9 views

Angular_JS_Complete_Document

The document provides an overview of key Angular and JavaScript concepts, including interceptors, RxJS, lifecycle methods, route guards, dependency injection, lazy loading, and optimization techniques. It includes code examples for implementing these concepts, such as an AuthInterceptor, usage of RxJS for data streams, and a simple login/signup application structure. Additionally, it covers JavaScript array manipulation techniques like reversing an array and removing vowels from words.

Uploaded by

anurag
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Angular_JS_Complete_Document

The document provides an overview of key Angular and JavaScript concepts, including interceptors, RxJS, lifecycle methods, route guards, dependency injection, lazy loading, and optimization techniques. It includes code examples for implementing these concepts, such as an AuthInterceptor, usage of RxJS for data streams, and a simple login/signup application structure. Additionally, it covers JavaScript array manipulation techniques like reversing an array and removing vowels from words.

Uploaded by

anurag
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Angular and JavaScript Concepts

What is an Interceptor in Angular?


An interceptor in Angular is a special service that intercepts and modifies HTTP requests
and responses. It is used for adding authorization headers, handling errors globally, logging
requests and responses, and modifying request/response payloads.

Example Implementation:

import { Injectable } from '@angular/core';


import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from
'@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authToken = localStorage.getItem('authToken');
const modifiedReq = req.clone({
headers: req.headers.set('Authorization', `Bearer ${authToken}`)
});
return next.handle(modifiedReq);
}
}

Registering the Interceptor:

providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
]

What is RxJS?
RxJS (Reactive Extensions for JavaScript) is a library for composing asynchronous and
event-based programs using observable sequences. It provides tools to work with streams
of data.

Example Usage:

import { of } from 'rxjs';


import { map } from 'rxjs/operators';

const data = of(1, 2, 3, 4);


data.pipe(
map(x => x * 2)
).subscribe(result => console.log(result)); // Output: 2, 4, 6, 8

Angular Lifecycle Methods


Angular components go through different lifecycle stages. Each stage is associated with a
lifecycle hook:

- ngOnInit: Called once after the component is initialized.


- ngOnChanges: Called when input-bound properties change.
- ngDoCheck: Called during every change detection cycle.
- ngAfterViewInit: Called after the component's view has been initialized.
- ngOnDestroy: Called just before the component is destroyed.

ViewChild and ContentChild


ViewChild is used to access elements or components from the same template, whereas
ContentChild is used to access elements projected into the component from other templates.

Example:

import { Component, ViewChild, ContentChild, ElementRef } from '@angular/core';

@Component({
selector: 'app-example',
template: `
<div #viewChildDiv>View Child Example</div>
<ng-content></ng-content>
`
})
export class ExampleComponent {
@ViewChild('viewChildDiv') viewChildDiv: ElementRef;
@ContentChild('contentChildDiv') contentChildDiv: ElementRef;

ngAfterViewInit() {
console.log(this.viewChildDiv.nativeElement.innerText);
console.log(this.contentChildDiv.nativeElement.innerText);
}
}

What are Route Guards?


Angular route guards control access to routes based on specific conditions. There are
several types of route guards including CanActivate, CanDeactivate, Resolve, and CanLoad.

Example:

@Injectable()
export class AuthGuard implements CanActivate {
canActivate(): boolean {
const isLoggedIn = !!localStorage.getItem('authToken');
return isLoggedIn;
}
}

Route Configuration:

{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }

What is Dependency Injection?


Dependency Injection (DI) is a design pattern in which components receive dependencies
from external sources rather than creating them.

Example:

@Injectable()
export class ApiService {
fetchData() {
return 'Data fetched!';
}
}

@Component({
selector: 'app-root',
template: '{{ data }}'
})
export class AppComponent {
data: string;
constructor(private apiService: ApiService) {
this.data = this.apiService.fetchData();
}
}

How to Implement Lazy Loading?


Lazy loading is a technique in Angular where feature modules are loaded on-demand rather
than at application startup.

Steps to implement lazy loading:

1. Generate a feature module using the Angular CLI:


ng generate module feature --route feature --module app.module
2. Configure the route with loadChildren:
const routes: Routes = [
{ path: 'feature', loadChildren: () => import('./feature/feature.module').then(m =>
m.FeatureModule) }
];

How to Optimize Angular Applications?


Key techniques to optimize Angular applications:

- Use Ahead-of-Time (AOT) Compilation.


- Implement lazy loading for feature modules.
- Use the OnPush change detection strategy.
- Minimize bundle size with tree-shaking.
- Optimize images and assets.

JavaScript Questions

Reverse an Array in JavaScript:

const array = [1, 2, 3, 4, 5];


console.log(array.reverse()); // Output: [5, 4, 3, 2, 1]

Remove Vowels from an Array:

const words = ['apple', 'orange', 'banana'];


const result = words.map(word => word.replace(/[aeiou]/gi, ''));
console.log(result); // Output: ['ppl', 'rng', 'bnn']

Angular Login/Signup Application


This example demonstrates how to create a login/signup application where the parent
component handles logic and API interactions, and the child component handles the display.

Parent Component:

@Component({
selector: 'app-root',
template: `<app-auth-form (formSubmitted)="onFormSubmitted($event)"></app-auth-
form>`
})
export class AppComponent {
onFormSubmitted(data: any) {
console.log('Form Data:', data);
// API call logic
}
}

Child Component:

<form (ngSubmit)="submitForm()">
<input [(ngModel)]="formData.username" name="username" placeholder="Username" />
<input [(ngModel)]="formData.password" name="password" placeholder="Password"
type="password" />
<button type="submit">Submit</button>
</form>

@Component({
selector: 'app-auth-form',
templateUrl: './auth-form.component.html'
})
export class AuthFormComponent {
@Output() formSubmitted = new EventEmitter<any>();
formData = { username: '', password: '' };

submitForm() {
this.formSubmitted.emit(this.formData);
}
}

You might also like