Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

Parameters in Date

Angular Pipes We can add parameter in pipe using : character.


These are also known as filters. They help We can show short, full or formatted dates
transform data and manage data within using this parameter. Add the code below in
interpolation, denoted by {{ | }}. It accepts data, the  app.component.html file.
arrays, integers and strings as inputs which are
separated by ‘|’ symbol. This module will cover
the use of pipes in detail.

Chained pipes
We can combine multiple pipes together.  This
will be useful when a scenario associates with
more than one pipe that has to be applied for
data transformation.  In the above example, if
Adding the parameters you want to show the date with uppercase
letters, then we can apply
Create a date method in both Date and Uppercase pipes together.
your app.component.ts file.

export class AppComponent {

presentDate = new Date();


Built-in Pipes
}
Angular supports the following built-in pipes
Now, add the below code in your namely AsyncPipe, CurrencyPipe, SlicePipe,
test.component.html file. DecimalPipe, PercentPipe, JSONPipe.

<div> AsyncPipe
Today's date :- {{presentDate}} If data comes in the form of observables,
</div> then Async pipe subscribes to an observable
and returns the transmitted values.
Now, run the application, it will show the
import { Observable } from 'rxjs';
following output −

Today's date :- Mon Jun 15 2020 10:25:05


GMT+0530 (IST)

In the example above, Date object is converted


into an easily readable format.
The Async pipe executes subscription for time
Adding the Date Pipe changing in every second and returns the result
whenever gets passed to it. Main advantage is
Now, add the date pipe in the html file as that, we don’t need to call subscribe on our
shown below. timeChange and there is no need to
unsubscribe, if the component is removed.
<div>
In the test.component.html, add the following:
Today's date :- {{presentDate | date }}
<div>
</div>
Seconds changing in Time: {{ todayO$ |
async | date:'mediumTime' }}
You should see the below output −
</div>

Today's date :- Jun 15, 2020


CurrencyPipe
This is used to convert the given number into
Reactive
various countries currency format. Add the
below code snippets
Programming
in app.component.ts and app.component.html 
This is a programming paradigm that deals with
files, respectively.
data streams and the spread of changes.
Streams of data can be static or dynamic. An
example of a static data stream is an array or
data collection. It's going to have an initial
quantity and it will not change.
As for dynamic data stream, examples are
events. Events emit the data whenever the
event occurs. Initially, there may be no events
but as the time progresses, events happens and
SlicePipe it will get emitted.

Slice pipe is used to return a slice of an array. It


takes index as an argument. If you assign only
start index, means it will print till the end of
values. If you want to print specific range of
values, then we can assign start and end index.

Reactive programming allows the data stream


to be emitted from one source
called Observable and the output data stream
to be caught by other sources
called Observer through a process
DecimalPipe called subscription. This Observable / Observer
pattern or simple Observer pattern simplifies
It is used to format decimal values. It is also complex change detection and necessary
considered as CommonModule. updating in the context of the programming.
JavaScript does not have the built-in support
for Reactive Programming. This is where RxJs is
helpful, it is a JavaScript Library which enables
reactive programming in JavaScript. Angular
uses RxJs library extensively to do below
mentioned advanced concepts −

 Data transfer between components.


 HTTP client.
 Router.
 Reactive forms.

There are other Angular Pipes available, below is Observable


list:
As learn earlier, Observable are data sources
and they may be static or
dynamic. Rxjs provides lot of method to
create Observable from common JavaScript
Objects. Let us see some of the common
methods.
function to subscribe to the Observable object.
They are as follows −
 next − Receive and process the value
emitted from the Observable
 error − Error handling callback
 complete − Callback function called
when all data from Observable are
emitted.
Once the three callback functions are defined,
Observable’s subscribe method has to be called
as specified below −
1. of − Emit any number of values in a sequence
and finally emit a complete notification. const numbers$ =
from([1,2,3,4,5,6,7,8,9,10]);
const numbers$ = of(1, 2, 3, 4, 5, 6, 7, 8,
9, 10); // observer

const observer = {
 numbers$ is an Observable object, next: (num: number) =>
which when subscribed will emit 1 to { this.numbers.push(num); this.val1 +=
10 in a sequence. num },
 Dollar sign ($) at the end of the
error: (err: any) => console.log(err),
variable is to identify that the
variable is Observable. complete: () =>
console.log("Observation completed")
2. range − Emit a range of number in sequence.
};

const numbers$ = range(1,10) numbers$.subscribe(observer);

3. from − Emit array, promise or iterable.  next − method get the emitted
number and then push it into the
const numbers$ = local variable, this.numbers.
from([1,2,3,4,5,6,7,8,9,10]);  next − method also adding the
number to local variable, this.val1.
4. ajax − Fetch a url through AJAX and then  error − method just writes the error
emit the response. message to console.
 complete − method also writes the
const api$ = ajax({ url: completion message to console.
'https://httpbin.org/delay/1', method:
'POST', headers: { 'Content-Type': We can skip error and complete method and
'application/text' }, body: "Hello" }); write only the next method as shown below −

5. fromEvent − Listen to an HTML element’s number$.subscribe((num: number) =>


event and then emit the event and its property { this.numbers.push(num); this.val1 +=
num; });
whenever the listened event fires.

const clickEvent$ =
fromEvent(document.getElementById('counter'), Operations
'click');
Rxjs library provides some of the operators to
Angular internally uses the concept extensively process the data stream. Some of the
to provide data transfer between components important operators are as follows −
and for reactive forms. filter − Enable to filter the data stream using
callback function.
Subscribing process
const filterFn = filter( (num : number) =>
Subscribing to an Observable is quite easy. num > 5 );
Every Observable object will have a method, const filteredNumbers$ = filterFn(numbers$);
subscribe for the subscription process.
Observer need to implement three callback
filteredNumbers$.subscribe( (num : number) =>
{

this.filteredNumbers.push(num); this.val2 +=
num } );

map − Enables to map the data stream using


callback function and to change the data stream
itself.

const mapFn = map( (num : number) => num +


num ); const mappedNumbers$ =
mappedFn(numbers$);

pipe − Enable two or more operators to be REST API and


combined.

const filterFn = filter( (num : number) =>


HTTP Client Setup
num > 5 );
This module introduces the Representational
const mapFn = map( (num : number) => num + State Transfer (REST) architectural style for
num ); const processedNumbers$ =
distributed hypermedia systems, describing the
numbers$.pipe(filterFn, mapFn);
software engineering principles guiding REST
processedNumbers$.subscribe( (num : number) and the interaction constraints chosen to retain
=> { this.processedNumbers.push(num); those principles, while contrasting them to the
this.val3 += num } );
constraints of other architectural styles.

Let us create a sample application to try out the REST is a hybrid style derived from several of
reaction programming concept learned in this the network-based architectural styles and
chapter. combined with additional constraints that
define a uniform connector interface. The
Create a new application, reactive using below software architecture framework is used to
command − define the architectural elements of REST and
examine sample process, connector, and data
ng new reactivedemo views of prototypical architectures.

Change the directory to the newly created Sharing data between two or more systems has
application. always been a fundamental requirement of
software development. For example, consider
cd reactive buying motor insurance. Your insurer must
obtain information about you and your vehicle
Create a new component called 'reactive' so they request data from car registration
authorities, credit agencies, banks, and other
Open the reactive.component.ts and code the systems. All this happens transparently in real-
following: time to determine whether a policy can be
offered.

Deriving REST
The rationale behind the Web architecture can
be described by an architectural
style consisting of the set
of constraints applied to elements within the
architecture. By examining the impact of each
constraint as it is added to the evolving style,
we can identify the properties induced by the
Web's constraints. Additional constraints can
then be applied to form a new architectural
style that better reflects the desired properties
of a modern Web architecture.
This section provides a brief overview of REST Figure 1. Resources list found on JSON
by walking through the process of deriving it as Placeholder Website
an architectural style. Later sections will
describe in more detail the specific constraints
that compose the REST style.

REST Constraints Procedure in setting up client


to fetch data from the server.
REST was defined in 2000 by Roy Fielding and
is considerably simpler. It’s not a standard but a In the previous project, add a new component
set of recommendations and constraints for called httpclient
RESTful web services. These include:
Create a new service with the same
1. Client-Server. SystemA makes an name httpclient
HTTP request to a URL hosted by
SystemB, which returns a response. In the main app.module.ts file, add the
following code:
It’s identical to how a browser works.
The application makes a request for a
specific URL. The request is routed
to a web server that returns an
HTML page. That page may contain
references to images, style sheets,
and JavaScript, which incur further
requests and responses.
2. Stateless. REST is stateless: the client
request should contain all the
information necessary to respond to
a request. In other words, it should
be possible to make two or more
HTTP requests in any order and the
same responses will be received.
3. Cacheable. A response should be
defined as cacheable or not.
4. Layered. The requesting client need
not know whether it’s
Figure 2. Importing the new components and
communicating with the actual
services created.
server, a proxy, or any other
intermediary. In the main httpclient.service.ts file,  instead of
indicating the data, we fetch the data from the
This lesson will require fetching a JSON API
JSON placeholder by pasting the URL:
located in the following
link: https://jsonplaceholder.typicode.com/Link
s to an external site.

 
Figure 3. Importing the new components and
services created.

  Let's take a closer look


  at httpclient.component.ts file below:
 
 
Figure 4. Modify the httpclient component file.
As seen on the above code, we have imported
the service created named HttpclientService,
then initialized a variable to store the data list
fetched from the JSON placeholder site.  In the
constructor (dependency injection), just like in
the previous activity, we inject the service we
previously created.
Lastly, we are now ready to display the data on
the browser.  A sample screenshot is shown
below.
 

 
Figure 5. Final output.

You might also like