Skip to content

Instantly share code, notes, and snippets.

@yogain123
Last active March 12, 2019 15:29
Show Gist options
  • Save yogain123/b19cee2a4a95176a5f05774811a13c3a to your computer and use it in GitHub Desktop.
Save yogain123/b19cee2a4a95176a5f05774811a13c3a to your computer and use it in GitHub Desktop.
Angular4
@yogain123
Copy link
Author

Reactive Form (Full Control)

<form [formGroup]="form">
	<input type="text" name="email" formControlName="email"/>
	<input type="text" name="password" formControlName="password"/>

  <div formGroupName="contact">
      <input type="text" name="firstName" formControlName="firstName">
      <input type="text" name="lastName" formControlName="lastName">
  </div>

	<button type="button" (click)="login()"></button>
<form>


controller
----------

 form = new FormGroup({
    email : new FormControl(),
    password : new FormControl(),
    contact : new FormGroup({
      firstName : new FormControl(),
      lastName : new FormControl()
    })
  });



login(){

  let credentials = this.form.value;
	console.log(credentials);
}

@yogain123
Copy link
Author

@yogain123
Copy link
Author

Observables

All Ajax request in Angular return observables
We can only subscribe to observables

to make your own observables

import { BehaviorSubject } from 'rxjs/BehaviorSubject';

  export class someService{ 

  private totalItems = new BehaviorSubject<number>(0);
  hola : number = 0;

  constructor(){}

  someFunction(){
  this.totalItems.next(this.hola);    //next is used to perform operations on      observables
  }

  getTotalItems(){     
      return this.totalItems;
  }
}

@yogain123
Copy link
Author

yogain123 commented Mar 19, 2018

Subscribe

If we subscribe to any observables and whenever there is a change in that observables (which will be in service mostly) then that change will be reflected on all those components where that observables is used (subscribed)

Take above example for own observables creation

now subscribe to that observables in some compoenet

this.someservice.getTotalItems().subscribe((item)=>this.something = item) //item is a returned observables from service

Subscribe to paramsMap

this.route.queryParamMap.subscribe(params=>{
      this.category = params.get("category")});  

unsubscribe

 ngOnDestroy(){
    console.log("inside component destroy");
    this.someservice.getTotalItems().unsubscribe();
  }

@yogain123
Copy link
Author

yogain123 commented Mar 19, 2018

Modules Seperations

screen shot 1939-12-29 at 1 12 34 am

Service can be used across all modules ,BUT components are specifics to its own modules , so in order to use components of one module into other , then we export that module and then IMPORT it wherever need

@yogain123
Copy link
Author

yogain123 commented Mar 19, 2018

Nested Routing

In Product.compoent.html
<router-outlet></router-outlet>

in app.module.ts

  {path: "products", component: ProductsComponent, children:[
        {path : "hola1",component:Hola1Component},
        {path : "hola2",component:Hola2Component}
      ]},

localhost:4200/products : PARENT.
localhost:4200/products/hola1 : CHILD
localhost:4200/products/hola2 : CHILD

@yogain123
Copy link
Author

@import "~bootstrap/dist/css/bootstrap.min.css";

@yogain123
Copy link
Author

yogain123 commented Mar 4, 2019

Throwing Error and Rollback changes

Rollback

screen shot 1940-12-14 at 12 35 37 am

Throwing Error
screen shot 1940-12-14 at 12 36 51 am

screen shot 1940-12-14 at 12 39 21 am

@yogain123
Copy link
Author

retry

retry is retrying observable call to server n number of times

screen shot 1940-12-14 at 12 41 59 am

@yogain123
Copy link
Author

yogain123 commented Mar 4, 2019

Route Params are Observable (usefull when we don't want to destroy the component but change it live on bases on different params)

subscribe to route params

screen shot 1940-12-14 at 12 54 52 am

@yogain123
Copy link
Author

subscribing to multiple observerable at once using switch map

screen shot 1940-12-14 at 1 07 22 am

screen shot 1940-12-14 at 1 08 33 am

screen shot 1940-12-14 at 1 10 13 am

@yogain123
Copy link
Author

yogain123 commented Mar 4, 2019

Programmatic Navigation

screen shot 1940-12-14 at 1 16 45 am

screen shot 1940-12-14 at 1 16 59 am

@yogain123
Copy link
Author

yogain123 commented Mar 4, 2019

Authentication and Authorization

Check what is JWT

screen shot 1940-12-14 at 1 38 30 am

screen shot 1940-12-14 at 1 38 40 am

screen shot 1940-12-14 at 1 41 03 am

@yogain123
Copy link
Author

yogain123 commented Mar 4, 2019

Check Token Expiration and all with help of jwt-helper global function tokenNotExpired()

npm install angular2-jwt --save

screen shot 1940-12-14 at 1 48 14 am

screen shot 1940-12-14 at 1 47 14 am

screen shot 1940-12-14 at 1 48 53 am

@yogain123
Copy link
Author

yogain123 commented Mar 4, 2019

Show and Hide Elements based on user roles

Show Admin link to only those user who is admin

screen shot 1940-12-14 at 1 53 44 am

screen shot 1940-12-14 at 1 54 30 am

screen shot 1940-12-14 at 1 55 16 am

@yogain123
Copy link
Author

Getting the current User

screen shot 1940-12-14 at 1 57 09 am

@yogain123
Copy link
Author

yogain123 commented Mar 4, 2019

Route Guard

implement CanActivate

screen shot 1940-12-14 at 2 01 25 am

screen shot 1940-12-14 at 2 00 40 am

screen shot 1940-12-14 at 2 26 32 am

@yogain123
Copy link
Author

yogain123 commented Mar 4, 2019

Improving User Experience for Routing User

canActivate Take 2 parametes

screen shot 1940-12-14 at 2 23 37 am

returnUrl : state.url

=========

screen shot 1940-12-14 at 2 28 23 am

let returnUrl = this.route.snapshot.queryParamMap.get("returnUrl");
this.router.navigate([returnUrl | "/"]);

@yogain123
Copy link
Author

making header and sending request

screen shot 1940-12-14 at 2 39 21 am

screen shot 1940-12-14 at 2 40 12 am

===================

The Very Same Thing with almost no code can be done using angular AuthHttp

screen shot 1940-12-14 at 2 41 08 am

@yogain123
Copy link
Author

yogain123 commented Mar 5, 2019

BehaviorSubject

The BehaviorSubject holds the value that needs to be shared with other components. These components subscribe to data which is simple returning the BehaviorSubject value without the functionality to change the value. Here is a more detailed breakdown of asObservable. In updateDataSelection we call next and pass in a new value to the BehaviorSubject.


All subscribers to a subject share the same execution of the subject. i.e. when a subject produces data, all of its subscribers will receive the same data. This behavior is different from observables, where each subscription causes an independent execution of the observable.

@yogain123
Copy link
Author

yogain123 commented Mar 5, 2019

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


@Injectable()
export class ShoppingkartService {

  private totalItems = new BehaviorSubject(null);
  hola : number = 0;

  constructor() { }

  addToShoppingKart(){
      this.hola++;
      this.totalItems.next(this.hola);
  }
  getTotalItems(){     
      return this.totalItems;
  }
}

======

In some component

 ngOnInit() {
    this.shoppingkartService.getTotalItems().subscribe(item=>{
      this.totalItems=item;
    })
  }

@yogain123
Copy link
Author

WE can Complete Observation using complete

completeMe(){
  this. totalItems.complete();
}

@yogain123
Copy link
Author

Create Your Own Observable

import { Observable } from "rxjs/Observable"

// create observable
const simpleObservable = new Observable((observer) => {
    
    // observable execution
    observer.next("bla bla bla")
    observer.complete()
})

// subscribe to the observable
simpleObservable.subscribe()

// dispose the observable
simpleObservable.unsubscribe()

@yogain123
Copy link
Author

Main Difference between Observables and Promise

Observables can have multiple values over time

Now if you keep that subscription to the newsletter open, you will get a new one every once and a while. The sender decides when you get it but all you have to do is just wait until it comes straight into your inbox.
If you come from the world of promises this is a key difference as promises always return only one value. Another thing is that observables are cancelable. If you don’t want your newsletter anymore, you unsubscribe. With promises this is different, you can’t cancel a promise

@yogain123
Copy link
Author

screen shot 1940-12-17 at 12 24 41 am

@yogain123
Copy link
Author

We Unscubscribe to overcome memory Leak
unscubscribe in OnDestroy()

Screen Shot 1940-12-19 at 4 39 50 PM

@yogain123
Copy link
Author

yogain123 commented Mar 10, 2019

Async Pipe

You don't have to subscribe to observable
you don't have to unsubscribe to observable
you don't have to implement ngOnInit

Screen Shot 1940-12-19 at 4 43 41 PM

@yogain123
Copy link
Author

As Keyword

it is used to give alias

Screen Shot 1940-12-19 at 4 45 38 PM

can we rewritten as

Screen Shot 1940-12-19 at 4 46 01 PM

@yogain123
Copy link
Author

@yogain123
Copy link
Author

yogain123 commented Mar 12, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment