Monday, March 15, 2021

Angular development with TypeScript note

 Angular development with TypeScript

1. source code

https://github.com/Farata/angulartypescript

forum:

https://forums.manning.com/forums/angular-development-with-typescript-2E

Although most of his books are printed, his Java Programming for Kids, Parents, and Grandparents is available for free download in several languages at http://myflex.org/books/java4kids/java4kids.htm.

2.

Angular is a component-based framework, and any Angular app is a tree of components.

A parent component can pass data to its child by binding the values to the child’s component property. A child component has no knowledge of where the data came from. A child component can pass data to its parent (without knowing who the parent is) by emitting events. This architecture makes components self-contained and reusable.

Most of the business logic of your app is implemented in services, which are classes without a UI. Angular will create instances of your service classes and will inject them into your components.

3.

You don’t need to modify dependencies in the package.json file manually. Run the ng update command, and all dependencies in package.json will be updated, assuming you have the latest version of Angular CLI installed. The process of updating your apps from one Angular version to another is described at https://update.angular.io

4.

ng g c— Generates a new component.

ng g s— Generates a new service.

ng g d— Generates a new directive.

ng g m— Generates a new module.

ng g application— Generates a new app within the same project. This command was introduced in Angular 6.

ng g library— Starting with Angular 6, you can generate a library project.

5.

For cleaner code separation, we usually don’t use a component for code that fetches or manipulates data. An injectable service is the right place for handling data. 

Note that the generated ProductService class is annotated with the @Injectable() decorator. To have Angular instantiate and inject this service into any component, add the following argument to the component’s constructor:

constructor(productService: ProductService){

  // start using the service, e.g. productService.getMyData();

}

Starting from Angular 6, provideIn: 'root' allows you to skip the step of specifying the service in the providers property of the NgModule() decorator.

6.

A directive can’t have its own UI, but can be attached to a component or a regular HTML element to change their visual representation. There are two types of directives in Angular:

Structural— The directive changes the structure of the component’s template. (like *ngFor, *ngIf)

Attribute— The directive changes the behavior or visual representation of an individual component or HTML element.

7.

Angular supports two types of data binding: unidirectional (default) and two-way. With unidirectional data binding, the data is synchronized in one direction: either from the class member variable (property) to the view or from the view event to the class variable or a method that handles the event.

Use square brackets to bind the value from a class variable to a property of an HTML element or an Angular component. 

<span [hidden]="isValid">This field is required</span>

This is unidirectional binding from the class variable to the view.

Remember, square brackets represent property binding, and parentheses represent event binding. To denote two-way binding, surround a template element’s ngModel with both square brackets and parentheses. 

[(ngModel)]="shippingAddress"

8.

In SPAs, you need the ability to modify the URL without forcing the browser to make a server-side request so the application can locate the proper view on the client. Angular offers two location strategies for implementing client-side navigation:

HashLocationStrategy. Changing any character to the right of the hash sign doesn’t cause a direct server-side request

PathLocationStrategy. This is the default location strategy in Angular.

To use hash-based navigation, @NgModule() has to include the providers value:

providers:[{provide: LocationStrategy, useClass: HashLocationStrategy}]

The <router-outlet> specifies the area on the page where the router will render the components (one at a time)


9.

By default the address bar of the browser changes as the user navigates with the router. If you don’t want to show the URL of the current route, use the skipLocationChange directive:

<a [routerLink]="['/product']" skipLocationChange>Product Details</a>


10.

A provider is an instruction to Angular about how to create an instance of an object for future injection into a target component, service, or directive. 

The long version would look like this: providers:[{provide: ProductService, useClass: ProductService}]. You say to Angular, “If you see a class with a constructor that uses the ProductService token, inject the instance of the ProductService class.”

@Injectable() is required only when the service itself has its own dependencies. It instructs Angular to generate additional metadata for this service. 

Providers declared in the @NgModule() decorator of a lazy-loaded module are available within such a module, but not to the entire application. 

providers of eagerly loaded modules are merged with providers of the root module. In other words, Angular has a single injector for all eagerly loaded modules.

11.

    of(1,2,3).subscribe(

      value=>console.log(value),

      err=>console.log(err),

      ()=>console.log("Streaming is over")

    );

    from(beers).pipe(

      map(beer=>beer.price),

      reduce((total,price)=>total+price,10)

    ).subscribe(

      beer=>console.log(beer),

      err=>console.log(err)

    );

12.

In a regular JavaScript app, to get a reference to the DOM element, you use a DOM selector API, document.querySelector(). In Angular, you can use the @ViewChild() decorator to get a reference to an element from a component template.

 <input type="text" #stockSymbol placeholder="Enter stock" >

   @ViewChild('stockSymbol') myInputField: ElementRef;

  constructor(){

  }

  ngAfterViewInit(): void {

    let keyup$ = fromEvent(this.myInputField.nativeElement, 'keyup');

    let keyupValue$ = keyup$.pipe(

      debounceTime(500),

      map(event => event['target'].value)

    ).subscribe(

      stock => this.getStockQuoteFromServer(stock)

    );

  }


  getStockQuoteFromServer(stock: string) {

    console.log(`The price of ${stock} is ${(100 * Math.random()).toFixed(4)}`);

  }

13.

In Angular, HTTP requests return observables. 

Angular doesn’t offer an API to support event bubbling. If event bubbling is important to your app, don’t use EventEmitter; use native DOM events instead.

14.

There are two approaches to working with forms in Angular: template-driven and reactive. 

Because you’re limited to HTML syntax while defining the form, the template-driven approach suits only simple forms.

With the reactive API, You construct the form model object explicitly using the FormControl, FormGroup, and FormArray classes.

To enable reactive forms, add ReactiveFormsModule from @angular/forms to the imports list of NgModule. For template-driven forms, import FormsModule

15.

NgForm is the directive that represents the entire form. It’s automatically attached to every <form> element.

16.

FormControl is an atomic form unit. FormGroup is a collection of FormControl objects and represents either the entire form or its part. When you need to programmatically add (or remove) controls to a form, use FormArray. It’s similar to FormGroup but has a length variable.

17.

[ngModelOptions]= "{updateOn:'blur'}" change/submit

18.

To notify BehaviorSubject about the new value, you use next(), and to notify the store about the new state, you use dispatch(). To get the new state, subscribe to the observable in both cases.

In ngrx apps, the Store service always remains a single source of truth, which may have multiple slices of state.

even though actions can be handled in both a reducer and an effect, only a reducer can change the state of an app.

Thursday, March 11, 2021

OAuth2 and Open Connect ID


OAuth2 and Open Connect ID in plain English, easy to understand 

https://www.youtube.com/watch?v=996OiexHze0

https://oauthdebugger.com





Wednesday, March 10, 2021

ng-book2-angular-6-r68 reading note

 


1. 

you can type the following commands to run any example:

npm install

npm start


2. Make sure node.js, typescript and Angular CLI are installed

npm -v

tsc -v

ng --version

ng    #to show the command list and get help


3. Run the below to create a new project from scratch

ng new angular-hello-world


4.

use the --port flag when running ng serve like this:

ng serve --port 9001


5. To create a new component using Angular CLI

ng generate component hello-world


6.

the ng serve command live-compiles our .ts to a .js file automatically.

Angular uses a concept called “style-encapsulation” which means that styles

specified for a particular component only apply to that component.

@Input() userId!: string; 

Now, the compiler understands that this variable, although not defined at compile time, shall be defined at run-time, and in time, before it is being used.

    <li *ngFor="let lolname of names">

        <app-user-item [name]="lolname"></app-user-item>

    </li>

define template between backticks(`...`) or sepearte file. 

Apostrophe

7. When we run "ng serve", ng will look at the file angular.json to find the entry point to our app.

angular.json specifies a "main" file, which in this case is main.ts

main.ts is the entry-point for our app and it bootstraps our application

We use the AppModule to bootstrap the app. AppModule is specified in src/app/app.module.ts


8. The methods

return a boolean value of false (tells the browser not to propagate the event upwards)


9. deploy

ng build --prod --base-href /

hosting on now:

install now: npm install -g now


10.

any is the default type if we omit typing for a given variable. Having a variable of type any allows

it to receive any kind of value:

var something: any = 'as string';

something = 1;


11.

When methods don’t declare an explicit returning type and return a value, it’s assumed they can

return anything (any type).

In TypeScript you can have only one constructor per class.

.forEach is a method on Array that accepts a function as an argument and calls that

function for each element in the Array.

var data = ['Alice Green', 'Paul Pfifer', 'Louis Blakenship'];

data.forEach(function(line) { console.log(line); });

Fat arrow => functions are a shorthand notation for writing functions.

data.forEach( (line) => console.log(line) );


12.

@Input('shortName') name: string;

@Input('oldAge') age: number;

<my-component [shortName]="myName" [oldAge]="myAge"></my-component>


13.

To create a custom output event we do three things:

1. Specify outputs in the @Component configuration

2. Attach an EventEmitter to the output property

3. Emit an event from the EventEmitter, at the right time


14.

The line [class.selected]="isSelected(myProduct)" is a fun one: Angular allows us to set

classes conditionally on an element using this syntax. This syntax says “add the CSS class selected

if isSelected(myProduct) returns true.” This is a really handy way for us to mark the currently

selected product.


15.

Here when we say @HostBinding('attr.class')

cssClass = 'item'; we’re saying that we want to attach the CSS class item to the host element. The host is the

element this component is attached to.


16.

<span *ngFor="let name of product.department; let i=index">


17.

<div [style.background-color]="'yellow'">

Uses fixed yellow background

</div>

<div [ngStyle]="{color: 'white', 'background-color': 'blue'}">


18.

A FormControl represents a single input field - it is the smallest unit of an Angular form.

FormControls encapsulate the field’s value, and states such as being valid, dirty (changed), or has errors.

<input type="text" [formControl]="name" />


19.

if you import FormsModule, NgForm will get automatically attached to any <form> tags you have in your view.

This is really useful but potentially confusing because it happens behind the scenes.

Learning Angular third edition reading note

 Learning Angular


1. Source code:

https://github.com/PacktPublishing/Learning-Angular--Third-Edition

2.

install VS Code extension "Angular Essentials"

In public methods and properties, we can omit the keyword public.

Remember, no more var; use the let keyword wherever possible.

number defines a floating-point number, as well as hexadecimal, decimal, binary, and octal literals.

you can come up with your own type:

type Animal = 'Cheetah' | 'Lion';

const animal: Animal = 'Cheetah';

3.

function sayHello(name: string): string {

    return 'Hello, ' + name;

}

to annoymous function:

const sayHello = function(name: string): string {

    return 'Hello, ' + name;

}

4.

TypeScript defines that a parameter is optional by adding the ? symbol as a postfix to the parameter name we want to make optional (place last):

function greetMe(name: string, greeting?: string): string {

    if(!greeting) {

        greeting = 'Hello';

    }

    return greeting + ', ' + name;

}

5.

default parameter (put last)

function greetMe(name: string, greeting: string = 'Hello'): string {

    return `${greeting}, ${name}`;

}

6.

rest parameter (put last)

function greetPeople(greeting:string,...names: string[]): string {

    return greeting + "," + names.join(" and ") + "!";

}

console.log(greetPeople("Hello","Ahri","Ashe"));

7.

const oldPerson = { name : 'John' };

const newPerson = { ...oldPerson, age : 20 };

9.

class Car {

    make: string;

    model: string;

    constructor(make: string, model: string) {

        this.make = make;

        this.model = model;

    }

}

TypeScript eliminates this boilerplate by using accessors on the constructor parameters.

class Car {

    constructor(public make: string, public model: string) {}

}

TypeScript will create the respective public fields and make the assignment automatically. 

10.

Can create an instance from an interface

interface A {

    a

}

const instance = <A> { a: 3 };

instance.a = 5;

console.log(instance.a);

This means you can create a mocking library very easily.

11.

To use it, we need to place the ? postfix in the nullable property, as follows:

for (let i = 0; i < hero.powers?.length; i++) {

}

Now, the if-else statement to check for nullable values is not needed anymore.

12.

Each member marked with the export keyword becomes part of the module's public API.

my-service.ts

export class MyService {

    getData() {}

}

export const PI = 3.14;

To use this module and its exported class, we need to import it:

import { MyService, PI } from './my-service';

13.

<span>{{ title }}</span>

same as 

<span [innerText]="title"></span>

while <span [innerText]="'My title'"></span> innerText property is a static string, not a component property.

14.

<p [class.star]="isLiked"></p>

The star class will be added to the paragraph element when the isLiked expression is true. Otherwise, it will be removed from the element. 

15.

template referance variable

<app-hero [name]="hero" #heroCmp (liked)="onLike(true)"></app-hero>

<span {{heroCmp.name}}></span>

16.

When using expressions that evaluate to a boolean value, it is best to use triple equality, ===, over the usual == because === checks not only whether values are equal but also whether types match. For example, 0 == '0' is truthy, whereas 0 === '0' is falsy.

17.

When we define an observable variable, we tend to append the $ sign to the name of the variable. This is a convention that we follow so that we can identify observables in our code efficiently and quickly.

18.

https://github.com/PacktPublishing/Learning-Angular--Third-Edition/tree/master/ch07

npm install angular-in-memory-web-api --save-dev

19.

By default it's for development.

ng build --prod


Saturday, February 27, 2021

Spring official document note

 https://docs.spring.io/spring-boot/docs/

1.

If you need to find out what auto-configuration is currently being applied, and why, start your application with the --debug switch. 

2.

To disable devtools, exclude the dependency or set the -Dspring.devtools.restart.enabled=false system property.

3.

With ApplicationStartup, Spring Framework allows you to track the application startup sequence with StartupSteps. This data can be collected for profiling purposes, or just to have a better understanding of an application startup process.

public static void main(String[] args) { SpringApplication app = new SpringApplication(MySpringConfiguration.class); app.setApplicationStartup(new BufferingApplicationStartup(2048)); app.run(args); }

4.

By default, SpringApplication converts any command line option arguments (that is, arguments starting with --, such as --server.port=9000) to a property and adds them to the Spring Environment. As mentioned previously, command line properties always take precedence over file based property sources.

If you do not want command line properties to be added to the Environment, you can disable them by using SpringApplication.setAddCommandLineProperties(false).

5.

Spring Boot does not provide any built in support for encrypting property values, however, it does provide the hook points necessary to modify values contained in the Spring Environment. The EnvironmentPostProcessor interface allows you to manipulate the Environment before the application starts. See Customize the Environment or ApplicationContext Before It Starts for details.

If you’re looking for a secure way to store credentials and passwords, the Spring Cloud Vault project provides support for storing externalized configuration in HashiCorp Vault.

6.

By default, if you use the “Starters”, Logback is used for logging. 

7.

Spring MVC uses the HttpMessageConverter interface to convert HTTP requests and responses. Sensible defaults are included out of the box. 

8.

By default, Spring Boot serves static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext. It uses the ResourceHttpRequestHandler from Spring MVC so that you can modify that behavior by adding your own WebMvcConfigurer and overriding the addResourceHandlers method.

9.

Spring Boot includes auto-configuration support for the following templating engines:

When you use one of these templating engines with the default configuration, your templates are picked up automatically from src/main/resources/templates.
10.

health

Shows application health information.

httptrace

Displays HTTP trace information (by default, the last 100 HTTP request-response exchanges). Requires an HttpTraceRepository bean.

info

Displays arbitrary application info.

integrationgraph

Shows the Spring Integration graph. Requires a dependency on spring-integration-core.

loggers

Shows and modifies the configuration of loggers in the application.

By default, all endpoints except for shutdown are enabled. To configure the enablement of an endpoint, use its management.endpoint.<id>.enabled property. 

* can be used to select all endpoints. For example, to expose everything over HTTP except the env and beans endpoints, use the following properties:
management.endpoints.web.exposure.include=* management.endpoints.web.exposure.exclude=env,beans

If Spring Security is present, endpoints are secured by default using Spring Security’s content-negotiation strategy. 

11.
If you are developing a web application, Spring Boot Actuator auto-configures all enabled endpoints to be exposed over HTTP. The default convention is to use the id of the endpoint with a prefix of /actuator as the URL path. For example, health is exposed as /actuator/health.
HTTP Tracing can be enabled by providing a bean of type HttpTraceRepository in your application’s configuration. For convenience, Spring Boot offers an InMemoryHttpTraceRepository that stores traces for the last 100 request-response exchanges, by default. InMemoryHttpTraceRepository is limited compared to other tracing solutions and we recommend using it only for development environments. For production environments, use of a production-ready tracing or observability solution, such as Zipkin or Spring Cloud Sleuth, is recommended. Alternatively, create your own HttpTraceRepository that meets your needs.




12.
Add
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

http://localhost:8080/actuator/beans
http://localhost:8080/actuator/env
http://localhost:8080/actuator/health
http://localhost:8080/actuator/httptrace   does not work
    The functionality has been removed by default in Spring Boot 2.2.0. 
http://localhost:8080/actuator/info 
http://localhost:8080/actuator/loggers
http://localhost:8080/actuator/metrics
http://localhost:8080/actuator/mappings 



Monday, February 22, 2021

Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud

 

https://github.com/PacktPublishing/Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud

 To see the code being executed, please visit the following: http://bit.ly/2kn7mSp.

 I prefer using constructor injection (over field and setter injection) to keep the state in my components immutable. 

 The immutable state is important if you want to be able to run the component in a multithreaded runtime environment.

Tuesday, February 9, 2021

Linux add user into group

 Command: 

sudo /usr/sbin/usermod -a -G jboss $USER (one time efffort in your login whenever VM rebuilt to allow to edit file in "jboss jboss")


The people can run himself and logout, re-login,

Check "groups THEID | grep jboss"