Monthly Archives: May 2018

Post/Put

Post:

  • Create new resources where server assigns Id.
  • update a set of resources
  • Will have an effect if same data issued multiple times.

Put:

  • Create a new object where the client takes the lead and assigns the Id
  • Update a resource using an id.
  • Will NOT have an effect if same data issued multiple times.

Angular – Route Guards

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

@Injectable()
export class PetGuard implements CanDeactivate {

  canDeactivate(component: PetComponent): Boolean {
     if(component.form.dirty) {
        return confirm('Navigate away? Your changes will be lost');
     }
     return true;
  }

}

Remember:

  • import the guard.. import { PetGuard } from ‘./pet-guard.service’;
  • register the guard as a provider
  • tie the guard to the route as seen in routing

Angular – Routing

Defining routes…

Here’s a complex route definition. You can add more using commas. This route allows an id to be passed to the route. Also a guard is setup allowing access to the controlled. The final element is the component who’s template will be activated:


{ path: 'pets/:id', canActivate: [ petsGuard], canDeactivate: [petsDeactivate], component: PetsComponent }

We can call routes within the application using:

pets

or for a button with variable id:

pets

We can use to tell the template where to display the routed element.

To get the parameter from the route:


import {ActiveRoute} from '@angular/router';

constructor(private route: ActivatedRoute)
{
}

then inside the constructor or onInit use a snapshot or an observable:

   

   let id = +this.route.snapshot.params['id'];

   ...or...

   this.subcription = this.route.params.subscribe(p=>
   {
      let id = +p['id'];  
   }

remember to unsubscribe!

Angular – Form Arrays

We can duplicate form controls or form groups using a form array.

  • Remember to setup a div with a form group when added to the component code.
  • build a function that creates the formgroups:

buildFields(): FormGroup {
return this.fb.group({
field1: '1',
field2: '2'
});
}

Replace the way we were building the fields inside the formgroup with calling the function:



this.customerForm = this.fb.group({
   fields: this.buildFields()
});

Create FormArray and replace the above code with:


this.customerForm = this.fb.group({   
   fields: this.fb.array([this.buildFields()])
});

Define a getter to allow the data to be retrieved:


get fields(): FormArray{
   return this.customerForm.get('fields');
}

where fields is the name of the form item on the html.  We need to add a div..




<[formGroupName]="i">
addField(): void {
   this.fields.push(this.buildField());
}