Submit value to backend using POST

Submitting to backend. The response type is set to <any> so it handle any properties returned in the response.

   this.http.post<any>('http://localhost:8080/getCustomerOrder', { name: 'Angular POST Request Example' }).subscribe(data => {
    console.log("- data id" + data.id);
 

Full example can be found at:

https://jasonwatmore.com/post/2019/11/21/angular-http-post-request-examples

Output variable from one component and receive by other component

This can be done through parent-child component relation. The child component will emit a value using EventEmitter. When adding the child component to a parent component’s template, the child component will have a binding mentioned which maps the emitting to a function in the parent component.

In the child component:

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

//... rest of Component

//inside the Component:
@Output()
  pricechange: EventEmitter<number> = new EventEmitter<number>();
  
//where we want to emit a change:
this.pricechange.emit(Number(getIngPrice));

In the parent component’s html template:

<!-- say we have a component with its name.
It will have pricechange which is emitted by the child component
in brackets, mapped to our function in the parent component-->
 <app-logic30-ingredients (pricechange)="changePrice($event)"></app-logic30-ingredients>

The parent component will have the function that receives the emit:

//a function in the component:

changePrice(priceEvent) {
    //alert("changePrice . got " + priceEvent);
    this.thePrice = this.thePrice + priceEvent;
}

Full example at https://ultimatecourses.com/blog/component-events-event-emitter-output-angular-2

Set and get attributes from HTML templates

Set an attribute by using square brackets, name of attribute, and its value:

<ng-container *ngIf="arrIngredients">
    <div id="ingsBox">  
        <div class="ing"
        id="{{'ing'+ing.id}}"
        [attr.name]="ing.name"
        (click)="toggleClick($event)"
        *ngFor="let ing of arrIngredients;">
            {{ing.name}} <br>
            <!-- {{ing.description}} -->
            <hr>
        </div>
    </div>
</ng-container>

Get it in the components via the getAttribute method, i.e.:

  toggleClick(event) { //example function
    alert(event.target.id);
    alert(event.target.getAttribute("name")); //getting it here.
  }

How to call an http method without the observable in Angular 2

Use .toPromise on the http get. You can then use this returned value in a promise if needed, i.e.:

getIngredient1(id2) {
  return this.http.get<ILogic10Ingredient[]>(
    "http://localhost:8080/logic10_base_ingredients/ingredient/"+id2).toPromise();
}

and:

              this.getIngredient1(this.ingAvailForUpdate).then
                (
                  (data2) => {
                    //alert("ing for: " + this.ingAvailForUpdate + ", " + data2[0].name)
                  }
                  ,
                  (err) => alert("err:" + err.message)
                );

The complete example can be found at https://stackoverflow.com/questions/38781162/how-to-call-an-http-method-without-the-observable-in-angular-2

localStorage and sessionStorage

For saving:

// clicks is the variable containing your value to save
localStorage.setItem('clickCounter', clicks);
// If you want to use the sessionStorage
// sessionStorage.setItem('clickCounter', clicks);

For loading:

const clicks = localStorage.getItem('clickCounter');
// If you want to use the sessionStorage
// const clicks = sessionStorage.getItem('clickCounter');

See https://stackoverflow.com/questions/58500879/implement-session-storage-in-an-angular-8-application for more examples

Angular techniques

Here is a list of some Angular techniques, useful when working with Angular applications

Submit value to backend using Post

Output variable from one component and receive by other component

Set and get attributes from HTML templates

How to call an http method without the observable in Angular 2

localStorage and sessionStorage

Subscribe to two observables whose results are needed

Click event

For loop in Angular

Receiving content through http get

Having paramterised routes work

Pass values from one component to another component

Get an incoming JSON object from a URL and work with it in your component

Include a component in another component

Have the application root show component links and the content

Setting up an Angular router

Subscribe to two observables whose results are needed

Use forkJoin to subscribe to more than one observable simultaneously

forkJoin(
  this.service.service1(), this.service.service2(), this.service.service3()
).subscribe((res) => {
  this.funcA(res[0], res[1], res[2]);
});

Another example is:

   forkJoin(
      this.logic10Service.getLogic10(this.item_id),
      this.http.get<ILogic10BaseCategory[]>(this.catsUrl_part1 + this.item_id + this.CatsUrl_part2)
    ).subscribe((res) => {
      console.log("- forkJoin returned " + res[0] + ", and " + res[1]);
      //can start interacting with res[0] and res[1]
      
    })

For more, see https://stackoverflow.com/questions/52317494/is-it-good-way-to-call-subscribe-inside-subscribe

Click event

Call a click event through (click) and call the function that should be initiated. Assuming I have a function in the component called showUpdateables(catName), I can have the following in the html template file:

    <ng-container *ngIf="arrCats">
    <span id="categoryBox" *ngFor="let cat of arrCats;" (click)="showUpdateables(cat.name)">
        {{cat.name}}
    </span>
    </ng-container>

Receiving content through http get

This example will get a typed array of http result through get:

    this.http.get<ILogic10BaseCategory[]>(this.baseCatsForIngsUrl).subscribe(data => {
      console.log("-- successfully got: " + data)
    });

This example will get any http result:

    this.http.get<any[]>(this.catsUrl).subscribe(data=> {
      this.arrCats = data;
      console.log("-arrCats[0]: " + this.arrCats[0]);
    });

More examples can be found at https://jasonwatmore.com/post/2019/09/06/angular-http-get-request-examples