0% found this document useful (0 votes)
11 views59 pages

Intro_Angular_1

angular classes tcs

Uploaded by

Sahu Sahu Subham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views59 pages

Intro_Angular_1

angular classes tcs

Uploaded by

Sahu Sahu Subham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to Angular

INTERNAL
25 Apr 2023
Agenda

Session 1

• Angular Introduction
• Typescript
• Understanding a Hello world Angular application
• Creating your first component
• Interpolation and Property Data Binding

Session 2

• Event Binding and References


• Two Way Binding
• Structural Directives
• Attribute Directives
• Template Driven Form

Document Name
-2- CONFIDENTIAL
Agenda…

Session 3

• Model Driven Form


• Model Driven Form Validation
• Service
• Http and Observables
• Routing and Navigation

Session 4

• CRUD using Angular (Array)


• CRUD using Angular (API)

Document Name
CONFIDENTIAL
Angular Introduction

• Angular is an open-source, JavaScript framework


written in TypeScript from Google.

• Its primary purpose is to develop single-page


applications.

• Angular 2 is completely based on components. It


consists of several components forming a tree structure
with parent and child components.

Document Name
CONFIDENTIAL
Angular Versions

Version Year Remarks

1.0 2010 It also referred as AngularJS designed especially for single-page web
apps.
2.0 2016 It is compatible with mobile devices. Moreover, Angular 2 can be able
to use ES5, ES6, or TypeScript to write the codes.
4.0 2017 Bug fixed version for Angular 2.0

5.0 2017 In this version, there is a Build Optimizer that created with the Angular
CLI by which allows you to apply build optimizer by default. ie; It
identifies code that can be removed at build time without side effects.
6.0 2018 Some new features added like, Angular Elements, Component Dev Kit,
Angular Material Starter Components, Library support, and Tree
Shakeable Providers
--- ---

14.0 2022 All GitHub issues are removed, No Dependency with Ng module. Uses
TypeScript 4.7

Document Name
CONFIDENTIAL
Angular JS v/s Angular 2.0

Angular JS Angular 2.0

JavaScript-based framework for creating SPA. Complete re-write of AngularJS version.

The architecture of Angular 2 is based on


The architecture of AngularJS is based on MVC.
service/controller.

AngularJS was not developed with a mobile base


Angular 2 is a mobile-oriented framework.
in mind.

AngularJS code can write by using only ES5, We can use ES5, ES6, Typescript to write an
ES6, and Dart. Angular 2 code.

Nowadays, the controllers are replaced by


Based on controllers whose scope is now over. components, and Angular two is completely
component based.

Factory, service, provider, value and constant are The class is the only method to define services in
used for services Angular2

Run on only client-side Runs on client-side & server-side

Document Name
CONFIDENTIAL
Typescript

• The JavaScript is a loosely typed and dynamic language. For eg;


let age = 42; // age is now a number
age = "Anoop"; // age is now a string
age = true; // age is now a Boolean

• Since the JS was meant to be a scripting language friendly to both


programmers and designers and used only to add functionality to websites.
• TypeScript was launched in 2012. It was developed and is currently
maintained by Microsoft.
• TypeScript is called a JavaScript superset, as TypeScript only adds certain
features to JavaScript.

Document Name
CONFIDENTIAL
TypeScript v/s JavaScript
Typescript Javascript
Object-oriented programming Prototype based language
language
It has a feature known as Static Not
typing
Supports Interfaces Not
TypeScript always points out the Since JavaScript is an interpreted
compilation errors at the time of language. This advantage is not there.
development (pre-compilation). So,
less run time errors.
TypeScript supports static/strong It is dynamically typed language
typing
Superset of JS with ES6 support, but
able to compile to any lower versions
also for the browser compatibility.
Generally, when we run our In JavaScript types are checked at
TypeScript file, TypeScript compiles run time. That means types are not
our code and at that point it checks checked until the program executes.
the types. Only if everything is ok Document Name
does the program run. CONFIDENTIAL
TypeScript Basics
• Types by Inference
If you don't declare a type at all, but TypeScript infers (guesses) it for you.

let str = "Hello World"; //The variable will be treated as a string


based on the initial value assigned.

• Declaring Types
For declaring a variable just add a colon and its type to the right of whatever
you're declaring.
let name: string = "Anoop";

• Interfaces
It is a mechanism used for creating objects.
interface Person {
name: string;
city: string;
age: number;
}

Document Name
CONFIDENTIAL
TypeScript Basics …
let myData: Person = {
name: "Anoop",
city: "Trivandrum",
age: 40
};

• Conditionals
It is a mechanism, suppose if I want to make a key conditional, allowing it to
be present or not.

interface Person {
name: string;
city: string;
age?: number;
}

Document Name
CONFIDENTIAL
TypeScript Basics …
• Unions
If we want a variable to be able to be assigned more than one different data
type, we can declare so by using unions.
interface Person {
name: string;
city: string;
age: number | string;
}

let myData: Person = {


name: "Anoop",
city: "Trivandrum",
age: 40 //Valid
};

let myData: Person = {


name: "Anoop",
city: "Trivandrum",
age: “40” //Valid
};
Document Name
CONFIDENTIAL
TypeScript Basics …
• for Loops : There are three versions of for loop.
1. The for loop is used to execute a block of code a given number of times,
which is specified by a condition. Fo Eg;
for (let i = 1; i <= 3; i++) {
console.log ("Step:" + i);
}
2. TypeScript includes the for...of loop to iterate and access elements of an
array, list, or tuple collection.

let arr = [10, 20, 30, 40];


for (var val of arr) {
console.log(val); // prints values: 10, 20, 30, 40
}
3. Another form of the for loop is for...in. This can be used with an array, list,
or tuple.
let arr = [10, 20, 30, 40];

for (var index in arr) {


console.log(arr[index]);
}

Document Name
CONFIDENTIAL
TypeScript Basics …
• Arrays
In typing functions, we can type its parameters as well as its return value.
let numbersArray: number[] = [1, 2, 3]; // It only accept
numbers in this array
let numbersAndStringsArray: (number | string)[] = [1,
"two", 3]; // Here it accept numbers and strings.

• Tuples
A tuple is a typed array with a pre-defined length and types for each index.
Tuples are great because they allow each element in the array to be a known
type of value.
// define our tuple
let employee: [number, string, string, number];

// initialize the values


employee = [1001, 'Anoop', 'Software Engineer',
25000.00];

// print
console.log(employee);
Document Name
CONFIDENTIAL
Angular Installation

 For Installing Angular, there are 2 prerequisites:

• Node.js : Install the required version from https://nodejs.org/en/download.

 After the installation use the command npm - v which will list the node
version.

 By installing Node.js, we have automatically installed the npm Package


manager which will be the base for installing angular in our system.

 Angular CLI : In the terminal/command type the command npm install -g


@angular/cli. This will install the Angular CLI, after installation we can
check it using the following command ng --version.

Document Name
CONFIDENTIAL
Hello world Angular application

 npm install -g @angular/cli //command to install angular CLI

 ng new hello-world // create the project

 cd hello-world // switch to the project folder

 ng serve // Start the application

Document Name
CONFIDENTIAL
Hello world Angular application

Create a new angular project using the below command;

ng new hello-world

Important files to be known

 package.json : This is file includes the details about package dependencies of the
project.

 tsconfig.json : This is the typescript compiler configuration file.

 styles.css : This is a global css file used by the angular application.

 index.html : This is the entry file for the angular application.

 main.ts : This file starts the AppModule from app.module.ts, and it can be used to define
global configurations. It describes how the application parts fit together. Every
application has at least one Angular module, the root module by default it is called as the
AppModule.

Document Name
CONFIDENTIAL
Hello world Angular application

In the application app folder, we can be able to see the following files. The below files were
created by default when we created new project using the angular-cli command.

• app.component.css : It will contain the specific style of the app component.

• app.component.html : Each component consists of an HTML template that declares


what renders on the page.

• app.component.spec.ts : This file contains unit tests for the main AppComponent.

• app.component.ts : This is the classes that interact with the .html file of the
component, which gets displayed on the browser.

• app.module.ts : This is the area where we can group the components, directives and
services, which are related to the application.

Document Name
CONFIDENTIAL
Hello world Angular application …

Start the application using the below command;

ng serve

Document Name
CONFIDENTIAL
Creating your first component

Components are the most basic UI building block of an Angular app. An Angular app
contains a tree of Angular components. For Eg;

• Class − This is a class which consists of properties and methods.

• Metadata − This is used to decorate the class and extend the functionality of the class.

• Template − This is used to define the HTML view which is displayed in the application.

Document Name
CONFIDENTIAL
Creating your first component…

Use the following CLI command to generate a component.

ng generate component <component name>

It will create a new folder (login) in your project as component

Document Name
CONFIDENTIAL
Creating your first component…

Following files will be created while you create the login component;

• login.component.css : is a CSS file for the component,

• login.component.html : is an HTML file for the component where we will write HTML
for a component.

• login.component.spec.ts : is a test file where we can write unit tests for a component

• login.component.ts : is the class file for a component.

All the component files in Angular should follow the following format:

<component-name>.component.<file-type>

Document Name
CONFIDENTIAL
Creating your first component…
login.component.ts
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
uname:String = "";
pass:String = "";
performLogin() {
if(this.uname==="Anoop" && this.pass==="Tata") {
alert('Login successfull...');
} else {
alert('Login failed!!!');
}
}
}export class LoginComponent {} Document Name
CONFIDENTIAL
Creating your first component…
login.component.html
<div>
User Name: <input [(ngModel)]="uname"><br/>
Password: <input type="password" [(ngModel)]="pass"><br/>
<button (click)="performLogin()">Login</button>
</div>

 Since we need to use this component in other components, we use the export keyword

 The decorator is the feature of typescript, this is going to attach the metadata with the
class beneath it.

 In Angular we have one root component, and all other components needs to live inside
the root component

Document Name
CONFIDENTIAL
Templates
• A template is nothing, but a screen used to interact with the component. It
consists of a TypeScript class, an HTML template, and a CSS style sheet.
• Usually, we can define template in two manner;

1) Using Template:
• In this case we are defining an inline view in component attribute template. For
Eg;

template: '
<div>
<h1>{{appTitle}}</h1>
<div>To Hello World</div>
</div>

This is known as an inline template.

Document Name
CONFIDENTIAL
Templates …
2) Using templateURL :
• In this case we are defining an inline view in component attribute template. For
Eg;

templateURL:
viewname.component.html
where, viewname is the name of the app component module. For eg;
app.component.html

Document Name
CONFIDENTIAL
Directives
A directive is a custom HTML element that is used to extend the functionalities of
HTML. Angular has the following directives that get called as part of the
BrowserModule module.

• ngif: The ngif element is used to add elements to the HTML code if it evaluates
to true, else it will not add the elements to the HTML code.

<div *ngIf = 'display'>Hello World</div>

• ngFor: The ngFor element is used to elements based on the condition of the For
loop

<div>
<ul *ngFor = 'let cnt of countryList'>
<li>{{cnt}}</li>
</ul>
</div> .

Document Name
CONFIDENTIAL
Introduction to Angular

Session 2

Document Name
CONFIDENTIAL
Interpolation
 Instead of hard coding the data in the html, what would be better is to have a
variable and assign value to it and get the data to the template. This can be
achieved using interpolation.

 We can bind the variable value to the view using double curly braces {{}}, What we
need to specify inside the property double curly brace {{}} is called interpolation.

 One - Way data binding is from the component property to the view.

app.component.ts
export class AppComponent {
name:string = ‘Ajay Kishan’;
}

app.component.html
Hello user: <b>{{name}}</b>

Document Name
CONFIDENTIAL
Property Data Binding
 String Interpolation and Property binding both are used for same purpose i.e. one-
way databinding.

 Property data binding uses square bracket for property binding


app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h1 [innerHtml]=‘name'></h1>
<input type=‘text’ [value]=‘name'>
`
})
export class AppComponent {
name : string = ‘Ajay Kishan';
}

Document Name
CONFIDENTIAL
Interpolation vs Property Data Binding

• When you need to concatenate strings, you must use interpolation instead of property
binding.

• Property Binding is used when you have to set an element property to a non-string data
value.

Document Name
CONFIDENTIAL
Event Binding
 Event Binding is the process of bind the events along with the methods.

 In data binding the data flows from the component to the view, So when the component
class properties changes the view gets modified.

 app.component.ts
import {
Component
} from '@angular/core';
@Component ({
selector: 'my-app',
templateUrl: 'app/app.component.html'
})
export class AppComponent {
Status: boolean = true;
clicked () {
if(this.status==true) {
this.status=false;
} else {
this.status=true;
} Document Name
CONFIDENTIAL
Event Binding…
 app.component.html
<div>
{{Status}}
<button (click) = "clicked()">Click</button>
</div>

• We are first just displaying the value of the Status property of our class.

• Then are defining the button html tag with the value of Click. We then ensure that the
click event of the button gets triggered to the clicked event in our class.

Document Name
CONFIDENTIAL
Two-way binding
 In angular, When ever we want to use two-way data binding, we use the ngModel
directives.

 To the ngModel we assign the property which we want to bind.

 And the ngModel needs to be wrapped with the [()] for two-way binding.

 In two-way binding, when ever the property in component changes the view changes and
whenever the view changes the property in component get change.

Note: Before using ngModel to achieve two-way data binding, It is very important to
import the FormsModule from @angular/forms in app.module.ts

FormModule will contain the ngModel directive.

 Using Two-way data binding, we can simultaneously change the data property and display
the change in the view.

 We assign to the ngModel, the property which we want to a bind

Document Name
CONFIDENTIAL
Two-way binding …
• Two-way binding combines property binding with event binding:
1) Property binding : Sets a specific element property.
2) Event binding : Listens for an element change event.

Document Name
CONFIDENTIAL
Two-way binding …
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hello',
template: `
User Name: <input type="text" [(ngModel)]="userName" ><br/>
{{userName}}`
})
export class HelloComponent implements OnInit {
constructor() { }
private _userName: string = “Virat Kohli";
get userName(): string {
return this._userName;
}
set userName(val: string) {
//do some extra work here
this._userName = val;
}
ngOnInit(): void {
}
}
Document Name
CONFIDENTIAL
Structural Directives
• Structural directives are directives which change the DOM layout by adding and
removing DOM elements.
• When structural directives are applied, they generally are prefixed by an asterisk, *, such
as *ngIf.
• Following are some of the commonly used Structural directives in Angular;
• *ngIf : It is used to dynamically add some elements based on certain
attributes/conditions.
<div *ngIf="employee" class="name">{{employee.name}}</div>
• ngFor : The *ngFor directive is used to repeat a portion of HTML template once per
each item from an iterable list (Collection).
<tr *ngFor="let emp of employees;">
<td>{{emp.name}}</td>
</tr>
• ngSwitch : This directive is applied to the inner elements with a match expression.
<div [ngSwitch]="day">
<div *ngSwitchCase="'Sun'">Today is Sunday</div>
<div *ngSwitchCase="'Mon'">Today is Monday</div>
<div *ngSwitchDefault>Invalid Day selected</div>
</div>
Document Name
CONFIDENTIAL
Structural Directives …
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'employee-app',
templateUrl:'./app/app.component.html',
styleUrls:['./app/app.component.css']
})
class Employee {
name: string="";
empId: number=0;
status: string="";
}
export class AppComponent
{
employees : Employee[] = [{name: 'Anoop', empId: 1001, status:
'Active'}, {name: 'Sham', empId: 1002, status: 'Active'}, {name:
'Mohit', empId: 1003, status: 'In Active'},{name: 'Saran', empId:
1004, status: 'Active'}];
}
Document Name
CONFIDENTIAL
Structural Directives …
app.component.html
<table class='table'>
<thead>
<tr>
<th>Employee Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let emp of employees;">
<td>{{emp.empId}}</td>
<td>{{emp.name}}</td>
</tr>
</tbody>
</table>

Document Name
CONFIDENTIAL
Attribute Directives
• Attribute directive changes the behavior of the dom element.
1) ngClass : It is used to dynamically apply multiple classes to the html element.
ngStyle becomes much more useful when the value is dynamic.
For Eg;
<ul *ngFor="let product of stockArray">
<li [ngClass]="{
'text-success':product.status === 'Available',
'text-primary':product.status === 'Reorder',
'text-danger':product.status === 'NA'
}">{{ product.name }}
</li>
</ul>
2) ngStyle : The values in the object literal that we assign to ngStyle can be JavaScript
expressions which are evaluated, and the result of that expression is used as the value
of the CSS property.
Fo Eg;
<span [ngStyle]="{'background-color':emp.status === 'Active' ?
'green' : 'red' }"></<span>

Document Name
CONFIDENTIAL
Attribute Directives …
• Both the NgStyle and NgClass directives can be used to conditionally set the look and
feel of the application.

• NgStyle gives us fine grained control on individual properties.

• But if we want to make changes to multiple properties at once, creating a class which
bundles those properties and adding the class with NgClass makes more sense.

Document Name
CONFIDENTIAL
Template Driven Form
• To get all the features of the form working, we need to import the FormsModule and import
it in the app.module.ts
import { FormsModule } from "@angular/forms";

• Anytime we use the form tag, angular attaches an ngForm directive, which attaches the
form value to it
ngForm
• Gives the form field value
• Indicates whether the form is in valid or in Invalid status, so in the form tag we can create
an ngForm directive and assign a reference to it.

<form #userForm="ngForm" (click)=“registerEmployee(userForm.value)">

• Here the instance of ngForm is assigned to the reference variable userForm


• Now this reference variable refers to the entire Form

Document Name
CONFIDENTIAL
Template Driven Form…
• The userForm has a property called value, which we are going to pass through the handler.
• We need to specify two things to indicate that it belongs to this form directive, a name
attribute and an ngModel directive
• E.g <input type="text" name="name" ngModel />
• We can also group certain tags using ngModelGroup

<div ngModelGroup="address">
<div>Street : <input type="text" name="street" ngModel /></div>
<div>Postal code : <input type="text" name="postalcode" ngModel /></div>
</div>
registerEmployee(value: any) {
console.log(value);
console.log("Name value is :"+value.name);
}

Document Name
CONFIDENTIAL
Introduction to Angular

Session 3

Document Name
CONFIDENTIAL
Model Driven Form
• In model driven from, as the name suggest a form is represented by a model and this
model is responsible for handling all the user interaction with the form
• We will be using 2 classes to create the model
– 1. FormControl : All input fields defined in HTML template are the instance of
FormControl.
– 2. FormGroup : It is an instance of a set of FormControl is referred as FormGroup

• Since every form is a combination of one or more FormControl, Form is inevitably a


FormGroup.
• We will use FormControl, when we have very few (maybe one or two) independent field
on your UI design, maybe an input. So, there is no need for a form tag.

• Simillarly we will use FormGroup, when we have a form that has multiple inputs,
dropdown, radio buttons. All of which you want to create a JSON object to pass in API.

Document Name
CONFIDENTIAL
Model Driven Form …
<form [formGroup]="userForm" (click)=userSubmit()>
<div>
<label>Name</label>
<input type="text" formControlName="name" />
</div>
<div>
<label>Age</label>
<input type="text" formControlName="age"/>
</div>
<div>
<label>City</label>
<input type="text" formControlName="city"/>
</div>
<div>
<label>PostalCode</label>
<input type="text" formControlName="postalCode"/>
</div>
<button type="submit">Submit</button>
Document Name
</form> CONFIDENTIAL
Model Driven Form Validation
• Angular provides a built-in Validator class, which supports the built in validations.
• Based on the error, we can provide a valid error message to the user

<form [formGroup]="userForm" (click)=userSubmit()>


<div>
<label>Name</label>
<input type="text" formControlName="name"
[Validators.required] />
</div>
<div *ngIf="userForm.controls['name'].hasError('required')">
Please enter a name
</div>
<button type="submit">Submit</button>
</form>

Document Name
CONFIDENTIAL
Service
• Service is a piece of reusable code that we will use across multiple components in our
application.
• Usually, components needs to access the data. We can write data access code in each
Component, but this is very inefficient and breaks the rule of single responsibility.
• The Component should focus on presenting the data to the user.
• The task of receiving data from the back-end server should be delegated to another
class called service class because it provides each Component with the data it needs.
• There are 3 steps to implement services in Angular;
– 1) Create a Service
– 2) Register the service
– 3) Declare dependency

ng generate service employeeservice

Document Name
CONFIDENTIAL
Service …
• Product.ts
export class Product {
constructor(productID:number, name: string , price:number) {
this.productID=productID;
this.name=name;
this.price=price;
}
productID:number ;
name: string ;
price:number;
}
• product.service.ts
import {Product} from './product'
export class ProductService{
public getProducts() {
let products:Product[];
products=[
new Product(1,'Memory Card',500),
new Product(2,'Pen Drive',750),
new Product(3,'Power Bank',100)
] Document Name
CONFIDENTIAL
return products;
Service …
• app.component.ts
import { Component } from '@angular/core';
import { ProductService } from './product.service';
import { Product } from './product';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent
{
products:Product[];
productService;
constructor(){
this.productService=new ProductService();
}
getProducts() {
this.products=this.productService.getProducts();
}
Document Name
} CONFIDENTIAL
Service … (Injecting to the module)
• product.service.ts
import { Injectable } from '@angular/core';
@Injectable(){
providedIn: "root"
}
export class ProductService {
constructor()
{ }
public getProducts() {
let products:Product[];
products=[
new Product(1,'Memory Card',500),
new Product(2,'Pen Drive',750),
new Product(3,'Power Bank',100)
]
return products;
}
};
Document Name
CONFIDENTIAL
Service … (Injecting to the module)
• app.module.ts

import { BrowserModule } from "@angular/platform-browser";


import { NgModule } from "@angular/core";
import { AppComponent } from "./app.component";
import { ProductService } from "./productService";
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [ProductService],
bootstrap: [AppComponent]
})
export class AppModule {}

Document Name
CONFIDENTIAL
Service … (Injecting to the module)
• app.component.ts
import { Component } from '@angular/core';
import { ProductService } from './productService';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
message: string = "";
constructor(private productService: ProductService ) {}
ngOnInit() {
this.products=this.productService.getProducts();
}
}

Document Name
CONFIDENTIAL
HttpClient
• Angular provides a client HTTP API to communicate with a server over the HTTP
protocol, to download or upload data and access other back-end services.
• The HttpClient service class in @angular/common/http.
• Before you can use HttpClient, you need to import the Angular HttpClientModule. Most
apps do so in the root AppModule. (app.module.ts)
app.module.ts

import { HttpClientModule } from '@angular/common/http';


import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [], Document Name
CONFIDENTIAL
HttpClient : Requesting data from a server - GET
• The HttpClient.get() method to fetch data from a server. The asynchronous method sends
an HTTP request and returns an Observable that emits the requested data when the
response is received.
• The get() method takes two arguments;
• the endpoint URL from which to fetch
• an options object that is used to configure the request. (like headers,params,
return type etc.)

loadUsers() {
this.http.get<any>('https://jsonplaceholder.typicode.com/users')
.subscribe({
next: data => {
console.log(data);
this.message=JSON.stringify(data);
},
error: error => {
this.message=error.message;
}
})
}

Document Name
CONFIDENTIAL
HttpClient : Sending data to a server - POST
• The HttpClient.post() sends the HTTP POST request to the endpoint.
• The post method parsed the body of the response as JSON and returns it. This is the
default behavior. If we want any other type, then we need to specify explicitly using the
observe & responseType options.
addPerson(person:Person): Observable<any> {
const headers = { 'content-type': 'application/json'}
const body=JSON.stringify(person);
this.http.post(this.baseURL + 'people',
body,{'headers':headers , observe: 'response'})
.subscribe(
response=> {
console.log("POST completed sucessfully. The response
received "+response);
},
error => {
console.log("Post failed with the errors");
},
() => {
console.log("Post Completed");
}
} Document Name
CONFIDENTIAL
Observables
• Observable in Angular is a feature that provides support for delivering messages
between different parts of a single-page application.
• Angular makes use of observables as an interface to handle a variety of common
asynchronous operations.
• For example: The HTTP module uses observables to handle AJAX requests and
responses. The Router and Forms modules use observables to listen for and respond
to user-input events.
• In Angular to implement Observable, needs to create an instance of a subscriber
function. Whenever a consumer wants to execute the function the subscribe() method
is called. This function defines how to obtain messages and values to be published.

Document Name
CONFIDENTIAL
Routing
• Routing in Angular allows the users to create a single-page application with multiple
views and allows navigation between them.
• Users can switch between these views without losing the application state and
properties.
• Create the navigation links inside the app component and then provide the “routerLink”
directive to each route and pass the route value to “routerLink” directive.
• Then add the routes to the routing.module.ts file and then import the routing.module.ts
into the app.module.ts file.

app.component.html
<span>
<ul>
<li><a routerLink="/" >Home</a></li>
<li><a routerLink="/login" >Login</a></li>
<li><a routerLink="/custlist" >List</a></li>
</ul>
</span>
<router-outlet></router-outlet>

Document Name
CONFIDENTIAL
Routing …
• app-routing.module.ts

import { NgModule } from '@angular/core';


import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { CustlistComponent } from
'./custlist/custlist.component';

const routes: Routes = [


{ path: 'login', component: LoginComponent },
{ path: 'custlist', component: CustlistComponent },
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Document Name
CONFIDENTIAL
Happy Learning !

You might also like