const EventEmiiter = require(‘events’);
const myEmitter = new EventEmiiter();
myEmitter.on(‘newSale’, stock => {
console.log(`Total No of Stocks are ${stock}`)
})
myEmitter.emit(‘newSale’, 9)
===============
const EventEmiiter = require(‘events’);
class Sales extends EventEmiiter{
constructor(){
super();
}
}
const myEmitter = new Sales();
====================
const exress = require(‘express’);
const app = express();
app.get(‘/’, (req, res)=> {
res.status(200).json({message: “from server”})
})
app.post(‘/’, (req, res)=>{
res.send(“you posted req”)
})
const port = 300;
express.listen(port, ()=>{
console.log(‘listen…’)
})
1. pipeTransform
@Pipe({
name : 'employeeFilter'
})
export class EmployeePipeFilter pipeTransform {
transform(employees: Employee[], searchTerm: string) : Employees[] {
if(!employees || !searchTerm){
return employees
}
return employees.filter(employee => employee.name.toLowerCase().indexOf(searchTerm) !=-1)
}
}
2. Chaining pipes :
We can chain multiple pipes together. This particularly helps in scenarios where we need to associate more than one pipe that needs to be applied, and the final output will be transformed with all the pipes applied.
The workflow or chains will be triggered and apply the pipes one after another. An example of the chain pipe syntax is given as follows:
{{today | date | uppercase | slice:0:4}}
import {validators, AbstractControl,NG_VALIDATORS} from '@angular/forms'
import {Directive} from '@angular/core'
@Directive({
selector: '[appSelectValidator]',
provider : [
provide : 'NG_VALIDATORS',
useExisting: SelectedValidator,
multi: true
]
})
export class SelectedValidator implements Validators {
validate(control: AbstractControl) : {[key:string]: any} | null {
return control.value == '-1' ? {'defaultSelected',true} : null
}
}
3. Authenticate :
const routes: Routes = [
{
path: '',
component: MasterLayoutComponent,
canActivate: [AuthGuard],
runGuardsAndResolvers: 'always',
children: [
{
path: '',
redirectTo: 'cti',
pathMatch: 'full'
},
{
path: 'users',
component: UsersComponent
},
{
path: 'crm',
children: [{ path: '', loadChildren: './crm/crm.module#CRMModule' }]
},
{
path: 'reasoncodes',
children: [
{
path: '',
loadChildren: './reason-codes/reason-codes.module#ReasonCodesModule'
}
]
}
4. ViewChildren
Hello.ts - Child Component
import {component, input} from '@angular/core'
@Component({
selector: 'hello',
template: `{{name1}}
`
})
export class HelloComponet {
@Input name1 : string;
}
===============
Hello {{name}}
{
@Input name:string;
}
import {component, AfterViewInit, QueryList, ViewChildren} from '@angular/core';
@Viewchildren (HelloComponet) hellos:QueryList
ngAfterViewInit(){
hello.forEach(hello => console.log(hello))
}
5.CanActivate
Router
ActivatedRouteSnapshot
RouterStateSnapShot
CanActivate
export class AuthGuard implements CanActivate {
canActivate(route: ActivatedRouteSnapShot, state; RouterStateSnapShot){
const currentUser = this.AuthenticationService.CurrentUser();
if(currentUser){
return true;
}
this.router.navigation(['/login'], queryParams: {returnUrl: state.url})
}
}
6.Interceptor
HttpRequest
HttpEvent
HttpHandler
HttpInterceptor
export class BasicAuthInterceptor implements HttpInterceptor {
constructor (private authenticataionSevice : AuthenticationService)
intercept(request: HttpRequest, next; HttpHandler) : Observable>{
const currentUser = authenticataionSevice.currentUserValue;
if(currentUser && currentUser.authData){
request = request.clone({
setHeaders: {
Authorization: `Basic ${currentUser.authData}`
}
})
}
}
return next.handle(request);
}
7.Observable & Subject
var obs$ : Observable = of(1,2,3);
obs$.subscribe(x => console.log())
===================
Appservice.ts
export class appservice {
sub: subject;
obs$: Observable;
private behSub: BehaviourSubject;
behObs$: Observable;
constructor(){
this.sub = new subject();
this.obs$ = this.sub.asObservable();
this.behSub = new BehaviourSubject(1000);
this.behObs$ = this.behSub.asObservable();
}
sendData(data: number){ this.sub.next(data);}
behavSendData(data: number){ this.behSub.next(data); }
}
hellocomponent.ts
this.appservice.sub.subscribe(x => {
console.log('From subject : ', x)
})
//this.appservice.sub.next('TestString'); - To avoid this use asObservable
this.appservice.obs$.subscribe(x => {
console.log('From Observable : ', x);
})
emit(){
this.appservice.sendData(4);
this.appservice.behavSendData(4);
}
app.component.ts
this.appservice.sub.subscribe(x => {
console.log('From subject : ', x)
})
this.appservice.obs$.subscribe(x=> {console.log ('From Subject', x)})
this.appservice.behObs$.subscribe(x=> {console.log ('From BehSubject', x)})
In Observable, when we call subscribe, it will trigger to start run.
Where as in Subject, when we call the subscribe , it will only do register. We can control when the subject trigger(emit) to start run.
BehaviourSubject : When we subscribe, it will trigger with initial value. BehaviourObservable will keep previous value in memory.
ReplySubject : keep in memory up to n number of items.
————————-
this.appservice.getAllusers().subscribe((data)=> this.users = data)
getAllusers():Observable
return this.http.get(‘api/users’)
}
————–
what-is-the-difference-between-a-observable-and-a-subject-in-rxjs
Observables
They are cold: Code gets executed when they have at least a single observer.
Creates copy of data: Observable creates copy of data for each observer.
Uni-directional: Observer can not assign value to observable(origin/master).
The code will run for each observer . If its a HTTP call, it gets called for each observer.
if its a service we want to share among all the components, it wont have latest result all new subscribers will still subscribe to same observable and get value from scratch
Unicast means can emit values from the observable not from any other component.
Subject
They are hot: code gets executed and value gets broadcast even if there is no observer.
Shares data: Same data get shared between all observers.
bi-directional: Observer can assign value to observable(origin/master).
If are using using subject then you miss all the values that are broadcast before creation of observer. So here comes Replay Subject
multicast, can cast values to multiple subscribers and can act as both subscribers and emmitter
2. angular2-difference-between-a-behavior-subject-and-an-observable
what-is-the-difference-between-promises-and-observables
JavaScript Promises Tutorial with Angular 7/8 Example
Subject, Observable, Promise API Calls
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Observable, Subject, BehaviorSubject} from 'rxjs';
import {forkJoin, of} from 'rxjs';
import {map, catchError} from 'rxjs/operators';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = '';
subEx : BehaviorSubject;
constructor(private http: HttpClient){
// const test$ = new Observable (s => {
// s.next('2');
// s.next('3');
// s.next('4');
// });
// test$.subscribe( x=> console.log(x));
// Code with pipeable operators in RxJS6
// forkJoin(
// this.http.get('https://jsonplaceholder.typicode.com/tod/') .pipe(map((res) => res), catchError(e => of('Oops!'))),
// this.http.get('https://jsonplaceholder.typicode.com/todos/') .pipe(map((res) => res), catchError(e => of('Oops!')))
// ).subscribe(res => console.log(res));
this.subEx = new BehaviorSubject (0);
this.subEx.subscribe(x=>console.log('After Subject Call : ',x))
}
EmitValue(){
this.subEx.next(2);
const promise = this.http.get('https://www.techiediaries.com/api/data.json').toPromise();
console.log(promise);
promise.then((data)=>{
console.log("Promise resolved with: " + JSON.stringify(data));
}, (error)=>{
console.log("Promise rejected with " + JSON.stringify(error));
})
}
ngOnInit(){
this.subEx.subscribe(x=>console.log('After Subject Call From Oninit : ',x))
}
}