Angular Udemy Full stack angular and springboot Udemy course - vidyasekaran/current_learning GitHub Wiki

ng new pw Just enter for those 2 questions - it installs libs and dependencies

npm start or ng serve Both same - to start a project

Full stack angular and springboot Udemy course git clone https://github.com/darbyluv2code/fullstack-angular-and-springboot.git

Pdf slides http://www.luv2code.com/download-full-stack-angular-and-springboot-pdf-slides

Guide on angular file structure https://angular.io/guide/file-structure

For example directives like ngfor,ngif etc https://angular.io/api/common-directives

Mock a Rest Service using SoapUI followed below and created a productMockService that listens @ http://localhost:8080/product/ and lists all products

https://iteritory.com/how-to-mock-rest-service-or-soap-web-service-using-soapui/

https://github.com/mstrutt/product-list/blob/master/products.json

Steps to create angular project and display table data

mkdir sales-project

cd sales-project

PS E:\udemy-angular-chad\sales-project> ng new sales-project (Generate Angular sales-project)

  1. Generate a New Component sales-person-list

PS E:\udemy-angular-chad\sales-project>ng generate component sales-person-list (Generate sales-person-list component)

  1. **Generate a class SalesPerson with in sales-person-list component **

PS E:\udemy-angular-chad\sales-project>ng generate class sales-person-list/SalesPerson (Generate SalesPerson class inside sales-person-list component)

  1. Write a constructor and populate SalesPerson

sales-person.ts

export class SalesPerson {

constructor(public firstName:string, public lastName:string, public email:string, public salesvolume:number)
{

}

}

  1. take selector: 'app-sales-person-list' from sales-person-list.component.ts and put it in app.component.html
  1. **Populate salesPersonList of SalesPerson with data in sales-person-list.component.ts **

salesPersonList: SalesPerson[] =[ new SalesPerson("Vidya","Sekaran","[email protected]",500000), new SalesPerson("Ram","Prabhu","[email protected]",600000), new SalesPerson("pinky","doo","[email protected]",750000), new SalesPerson("doora","Sekaran","[email protected]",560000), new SalesPerson("Keera","Sekaran","[email protected]",320000) ]

  1. Display the salesPersonList in sales-person-list.component.html (Access the salesPersonList object present in sales-person-list.component.ts) populated in sales-person-list.component.ts -
    <tr>
        <th>FirstName</th>
        <th>LastName</th>
        <th>Email</th>
        <th>sales volume</th>

    </tr>
</thead>
<tbody>
    <tr *ngFor="let tmpsalesperson of salesPersonList">
        <td>{{tmpsalesperson.firstName}}</td>
        <td>{{tmpsalesperson.lastName}}</td>
        <td>{{tmpsalesperson.email}}</td>
        <td>{{tmpsalesperson.salesvolume}}</td>
    </tr>
</tbody>

Integrate angular with bootstap

  1. Apply bootstrap to the html table

Go to https://getbootstrap.com/docs/5.0/getting-started/introduction/ copy bolded 2 lines meta and link from Starter template and add it in our project index.html head section

** **

<title>SalesProject</title>
  1. app.component.html add bootstrap class such as "container" in div, mt-3 and mb-3 in h1

Sales Data

  1. Create a bootstrap html file by copy sales-person-list.component.html and paste as sales-person-list-bootstrap.component.html below mentioned

bootstrap class="table table hover" and class="thead-dark" added...

  1. update typescript component to reference bootstrap html template - sales-person-list.component.ts modify

Old : templateUrl: './sales-person-list.component.html', New : templateUrl: './sales-person-list-bootstrap.component.html'

Angular for Conditionals and Formatting

ngIf - show content based on conditional /boolean expression

show data

Modify sales-person-list-bootstrap.component.html to include below added header

and MetQuoto value part which is based on "tmpsalesperson.salesvolume >500000;
Met Quoto
500000; else myelseblock"> Yes
No
    <tr>
        <th>FirstName</th>
        <th>LastName</th>
        <th>Email</th>
        <th>sales volume</th>
      **  <th>Met Quoto</th>**

    </tr>
</thead>
<tbody>
    <tr *ngFor="let tmpsalesperson of salesPersonList">
        <td>{{tmpsalesperson.firstName}}</td>
        <td>{{tmpsalesperson.lastName}}</td>
        <td>{{tmpsalesperson.email}}</td>
        <td>{{tmpsalesperson.salesvolume}}</td>
        <td>
            <div *ngIf="tmpsalesperson.salesvolume >500000; else myelseblock"> Yes</div>
            <ng-template #myelseblock>No</ng-template>
        </td>
    </tr>
</tbody>

Formatting sales volume with Angular Pipes - CurrencyPipe, DatePipe, DecimalPipe etc

{{tmpsalesperson.salesvolume | currency: 'USD'}}

FirstName LastName Email sales volume Met Quoto

Vidya Sekaran [email protected] $500,000.00 No

Ram Prabhu [email protected] $600,000.00 Yes

Real Time ECommerece App

  1. Show List of Products

  2. Add products to shopping cart (CRUD)

  3. Shopping cart check out

  4. user login/logout security

  5. Track previous orders for logged in users.

Steps

  1. Create New Project and add bootstrap syling by adding boostrap links in index.html

PS E:\udemy-angular-chad> ng new angular-ecommerce

  1. Generate Angular Component for product-list

PS E:\udemy-angular-chad>ng generate component components/product-list (generate files kept in sub-directory components)

NOTE: you need to copy the selector : app-product-list from product-list.component.ts to app.component.html --

  1. Develop TypeScript class for Product

PS E:\udemy-angular-chad>ng generate class common/product

We have SoapMock REST Service which returns below list of json tags for product service

SoapMock Project is present in E:\udemy-angular-chad\Ecommerce_Udemy_Chad if you want to import run this project and hit http://localhost:8080/product which returns list of product.

Soap project refer - https://iteritory.com/how-to-mock-rest-service-or-soap-web-service-using-soapui/

for product json refer: https://github.com/mstrutt/product-list/blob/master/products.json

export class Product { name: string; detail: string; price: string; hero: string; image: string; }

  1. Create Angular service to call Rest API

ng generate service services/product

service is typescript, its a helper class which provides desired functionality and its part of angular application which runs in the web browser client side.

Rest client provided by angular HttpClient part of HttpClientModule

  1. Now Add support in the application module src/app/app.module.ts

    a. In imports -- add HttpClientModule

    imports: [ BrowserModule, HttpClientModule ],

b. In provider add

 providers: [ProductService]  

c. manually add

 import {HttpClientModule} from '@angular/common/http';
 import {ProductService} from './services/product.service';
  1. Develop angular to subscribe to data in .ts file u do this

  2. Display html using *ngFor

  3. In product.service.ts add

import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Product } from '../common/product'; import {map} from 'rxjs/operators'

@Injectable({
    providedIn: 'root'
})

export class ProductService {

private baseUrl='http://localhost:8080/product';

constructor(private httpClient:HttpClient) { } -- inject HttpClient

getProductList(): Observable<Product[]>{

return this.httpClient.get<GetResponse>(this.baseUrl).pipe(
  map(response => response._embedded.products)                      -- map is from rxjs/operator - javascript reactive
);

} }

interface GetResponse{ ---- To map _embedded:{ products: Product[]; } }

  1. Inject ProductService written in 7 into product-list.component.ts

import { Component, OnInit } from '@angular/core'; import { Product } from 'src/app/common/product'; import { ProductService } from 'src/app/services/product.service';

@Component({ selector: 'app-product-list', templateUrl: './product-list.component.html', styleUrls: ['./product-list.component.css'] }) export class ProductListComponent implements OnInit {

products:Product[];

constructor(private productListService:ProductService) { }

ngOnInit() { this.listProduct(); }

listProduct(){
  this.productListService.getProductList().subscribe(
    data=>{
      this.products=data;
    }
  )
}

}

9.Display data in HTML product-list.component.html

{{prd.name}} : {{prd.price | currency: 'USD'}}

ng serve --open

Getting below error

Access to XMLHttpRequest at 'http://localhost:8080/product' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Reference : https://stackoverflow.com/questions/56328474/origin-http-localhost4200-has-been-blocked-by-cors-policy-in-angular7

In SOAPUI Mock service in header we added below 2

Access-Control-Allow-Origin * Access-Control-Allow-Methods GET,POST,OPTIONS,DELETE,PUT

In Angular service we used below recommendation - to fetch Non-Typed Response and its invoked in product-list.component.ts

For Product CRUD we need to use below url

https://www.djamware.com/post/5b87894280aca74669894414/angular-httpclient-678910-consume-rest-api-example#:~:text=in%20your%20application.-,Create%20Angular%20Service%20for%20consuming%20REST%20API%20using%20Angular%20HttpClient,press%20%60CTRL%2BC%60.&text=Next%2C%20open%20and%20edit%20%60src%2Fapp%2Frest.

getProducts(): Observable { return this.http.get(endpoint + 'products').pipe( map(this.extractData), catchError(this.handleError) ); }

private extractData(res: Response): any { const body = res; return body || { }; }

If you have written spring boot you need to enable @CrossOrigin support for spring boot applicatin.


Application diagram

Browser - sevices -----------Rest API ----------> SOAP UI

⚠️ **GitHub.com Fallback** ⚠️