Saturday, April 13, 2019

HostBinding, HostListener

A quick tip that helps me remember what they do -
HostBinding('value') myValue; is exactly the same as [value]="myValue"
And
HostListener('click') myClick(){ } is exactly the same as (click)="myClick()"



Wednesday, April 10, 2019

viewChild, viewChilden, contentChild

View Child:

Supported selectors include:
  • any class with the @Component or @Directive decorator
  • a template reference variable as a string (e.g. query <my-component #cmp></my-component> with @ViewChild('cmp'))
  • any provider defined in the child component tree of the current component (e.g. @ViewChild(SomeService) someService: SomeService)


REF:

ViewChild:
 https://dev.to/danielpdev/how-to-use-viewchild-decorator-in-angular-9-i0 (*******) (desc about static= true and false)

When should you use { static: true } ?

One usecase could be, when you need to access a child element's instance fields that don't rely for their values on inputs from other elements.

like i use in datatable for cellTemplat. Here i need only ref . not need viewchild element value.. (study https://dev.to/danielpdev/how-to-use-viewchild-decorator-in-angular-9-i0  for beter understanding)

When you assign "true" you can get ref in ngoninit lifecycle hook



 viewChildren

https://stackoverflow.com/questions/51252429/angular-viewchild-for-dynamic-elements-inside-ngfor



contentChild

https://www.udemy.com/the-complete-guide-to-angular-2/learn/lecture/6656114#overview


RouterModule.forChild(routes) and RouterModule.forRoot(routes)

https://medium.com/@cyrilletuzi/understanding-angular-modules-ngmodule-and-their-scopes-81e4ed6f7407 (VVI)

Preload Lazy loading: 

angular tutorial 299 (very important for lazy load module fating load)


Tuesday, April 9, 2019

Observables(cold and hot), Observers & Subscriptions, RxJS, subject, Subscription


Obserable vs promise

https://morioh.com/p/726c7646cc64 (*************** VVVVI)


Observables, Observers & Subscriptions

Observables:  An observable is a function that produces a stream of values to an observer over time. Example : Youtube,

Observers :
  1. When you subscribe to an observable, you are an observer. Ex: Human, You. Be we click on subscriber button on youtube;
  2. An observable can have multiple observers
Subscriptions:
  1. when we (man) subscribe the obserables then that is call subscriptoion

We can create obserable by "create()" method

import { Observable } from "rxjs/Observable";
var observable = Observable.create((observer:any) => {
    observer.next('Hey guys!')
}) 
Above, you can see that we're defining the subscribe function, and we're 
emitting a single value of 'Hey guys!' by calling observer.next().

Now, how can we subscribe or create a subscription to this observable?  Simple..

var observable = Observable.create((observer:any) => {
    observer.next('Hey guys!')
})

observable.subscribe((x:any) => console.log(x));
 
 
Please see the reference.... 
 
 
REF:
  • https://coursetro.com/posts/code/148/RxJS-Observables-Tutorial---Creating-&-Subscribing-to-Observables 
    https://www.learnrxjs.io/operators/creation/create.html 
 
  
You can use these creation operators that create observables in a variety of ways:
  • Of
  • FromEventPattern
  • FromEvent
  • FromPromise
  • Interval
  • Range
  • Timer
  • Empty
  • Throw
  • Never


RxJS Operators:

 Operator is used to operate some operation on obserable data;
example: Map(), filter(), first()



Cold and Hot Observable:

 When the data is produced by the Observable itself, we call it a cold Observable. When the data is produced outside the Observable, we call it a hot Observable.

REf:
https://medium.com/@luukgruijs/understanding-hot-vs-cold-observables-62d04cf92e03


 

Subjects:

memory leak possibility nai that way we use subject instead of objerable

  1. A Subject is like an Observable. It can be subscribed to, just like you normally would with Observables.  
  2. The main reason to use Subjects is to multicast. An Observable by default is unicast.
  3. Subjects are like EventEmitters, they maintain a registry of many listeners.  
  4. subject use to implement better uses of hot obserable
  5. there are some example to understand, please visit below reference link

Ref:



Subscription:

What is a Subscription? A Subscription is an object that represents a disposable resource, usually the execution of an Observable. A Subscription has one important method, unsubscribe, that takes no argument and just disposes the resource held by the subscription.



Angular HttpClient: 
  •  Before you can use the HttpClient, you need to import the Angular HttpClientModule. Most apps do so in the root AppModule.
  •  
  • import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    @Injectable()
    export class ConfigService {
      constructor(private http: HttpClient) { }
    } 
    
    
    
    
    this.http.get/ this.http.post return  Observable
     
    so to get the data write code somthing like
     
    this.configService.getConfig()
        .subscribe((data: Config) => this.config = {
            heroesUrl: data['heroesUrl'],
            textfile:  data['textfile']
        }) 
     
  • https://angular.io/guide/http


Try to use combineLatest instead of forkJoin :

With combineLatest :

const combined = Observable.combineLatest(
  this.http.get('https://testdb1.firebaseio.com/.json').map((res: Response) => res.json()),
  this.http.get('https://testdb2.firebaseio.com/.json').map((res: Response) => res.json())
)

combined.subscribe(latestValues => {
    const [ data_changes , data_all ] = latestValues;
    console.log( "data_changes" , data_changes);
    console.log( "data_all" , data_all);
});

You can also handle it by forkJoin , but forkJoin will return data when all calls are finished and return result , but in combineLatest When any observable emits a value, emit the latest value from each.

With forkJoin :

const combined = Observable.forkJoin(
  this.http.get('https://testdb1.firebaseio.com/.json').map((res: Response) => res.json()),
  this.http.get('https://testdb2.firebaseio.com/.json').map((res: Response) => res.json())
)

combined.subscribe(latestValues => {
    const [ data_changes , data_all ] = latestValues;
    console.log( "data_changes" , data_changes);
    console.log( "data_all" , data_all);
});

Call both and check the console log , you will get idea.




Angular learing important linlk (RxJS, Obserable, subscribe, subscription, ) switchmap, multiple time http call in Rxjs


how to use combine latest - you can pass as array or without array see the bellow example


combineLatest(
[this.FBD.iterateReferencesByChild('facilityData/' + this._currentFacility + '/tasks', 'parent/device', deviceId),
this.FBD.iterateReferencesByChild('facilityData/' + this._currentFacility + '/components', 'parent/device', deviceId),
this.FBD.iterateReferencesByChild('facilityData/' + this._currentFacility + '/attachments', 'parent/device', deviceId),
this.FBD.iterateReferencesByChild('facilityData/' + this._currentFacility + '/comments', 'parent/device', deviceId)]
).pipe(take(1)).subscribe((refArrays) => {
console.log("testing ",refArrays);
let referencePaths = [].concat.apply([], refArrays);
for (let i = referencePaths.length - 1; i >= 0; i--) {
references[referencePaths[i]] = null;
}
references['facilityData/' + this._currentFacility + '/devices/' + deviceId] = null;
this.logHelperService.markRemovedEvents(deviceId, '_deviceIndex');
Object.keys(references).forEach(element => {
// console.log(element);
const itemsRef = this.ngFireDb.list(element);
itemsRef.remove();
});
callback('done');
});


deleteDevice(deviceId, callback) {
let references = {};
combineLatest(
this.FBD.iterateReferencesByChild('facilityData/' + this._currentFacility + '/tasks', 'parent/device', deviceId),
this.FBD.iterateReferencesByChild('facilityData/' + this._currentFacility + '/components', 'parent/device', deviceId),
this.FBD.iterateReferencesByChild('facilityData/' + this._currentFacility + '/attachments', 'parent/device', deviceId),
this.FBD.iterateReferencesByChild('facilityData/' + this._currentFacility + '/comments', 'parent/device', deviceId)
).pipe(take(1)).subscribe((refArrays) => {
let referencePaths = [].concat.apply([], refArrays);
for (let i = referencePaths.length - 1; i >= 0; i--) {
references[referencePaths[i]] = null;
}
references['facilityData/' + this._currentFacility + '/devices/' + deviceId] = null;
this.logHelperService.markRemovedEvents(deviceId, '_deviceIndex');
Object.keys(references).forEach(element => {
// console.log(element);
const itemsRef = this.ngFireDb.list(element);
itemsRef.remove();
});
callback('done');
});
}




combine latest with another api call in pipe



getFacilitiesByUser(uid) {
return this.getFacilityRightsByUser(uid).snapshotChanges().pipe(
switchMap((data: any) => {
return combineLatest(
// of(data),
combineLatest(data.map(item => {
return this._getFacilityObject(item.key).snapshotChanges().pipe(map((action: any) => action))
}))
)
}),
map(([facData]) => {
return facData.map((item: any) => {
let obj: any = item.payload.toJSON();
return {
...obj,
'$id': item.key
};
});
})
)
}





debouncing
export class App {
  items: Array<string>;
  term = new FormControl();
  constructor(private wikipediaService: WikipediaService) {
    this.term.valueChanges
             .debounceTime(400)
             .subscribe(term => this.wikipediaService.search(term).then(items => this.items = items));
  }
}



toPromise()  // use obserable to promise() // I used in serverless async and await in s3 sdk
return this.jsonp
                .get('http://en.wikipedia.org/w/api.php?callback=JSONP_CALLBACK', { search })
                .toPromise()
                .then((response) => response.json()[1]);
fromPromise()  /// it use in obserable from promise

VVVI ( multiple time http call)

return new BehaviorSubject(null).pipe(
switchMap(size => this.ngFireDb.list(this.FBD.components(parent.facility), ref => ref.child(parent.component)).snapshotChanges()),
map((sn: any) => {
sn.map(item =>{
if(item.key == 'name'){
retString = item.payload.toJSON();
// console.log('name', item.payload.toJSON());
}
});
return retString;
}),
switchMap(retString => this.ngFireDb.list(this.FBD.devices(parent.facility), ref => ref.child(parent.device)).snapshotChanges()),
map((sn: any) => {
let devicename ='';
sn.map(item =>{
if(item.key == 'name'){
devicename = item.payload.toJSON();
}
});
return devicename+ ' - ' + retString;
})
);










Autoboxing and Unboxing

  Autoboxing  is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper cl...