You are on page 1of 38

Angular | Lecture 4

Marina Magdy
Agenda

● Recap previous lecture points


● Get data from JSON file
● Parameterised Routes
● Dependency Injection & Services
● Behavior Subject
● HTTP requests
How to read json file in Angular!

In tsconfig.ts under compileOptions Object please add the following to


properties to be able to work with json files in Angular Ts files.

"resolveJsonModule": true,

"esModuleInterop": true

}
Routing
Routing

● In a single-page app, you change what the user sees by showing or hiding
portions of the display that correspond to particular components, rather
than going out to the server to get a new page. As users perform
application tasks, they need to move between the different views that you
have defined.

● To handle the navigation from one view to the next, you use the Angular
Router. The Router enables navigation by interpreting a browser URL as an
instruction to change the view.
Routing
The advantages of an SPA are:

● Can be faster. Instead of making a time-consuming request to a far away


server every time the URL changes the client app updates the page much
faster.
● Less bandwidth required. We don’t send over a big HTML page for every
URL change, instead we might just call a smaller API which returns just
enough data to render the change in the page.
● Convenience. Now a single developer can build most of the functionality of
a site instead of splitting the effort between a front-end and server-side
developer.
Route Configuration

There are fundamental building blocks to creating a route :

● Import the AppRoutingModule into AppModule and add it to the


imports array.
● Import RouterModule and Routes into your routing module.
● Define your routes in your Routes array into your routing module.
● Add your routes to your application using routerLink and update your
component template to include <router-outlet>. This element informs
Angular to update the application view with the component for the selected
route.
Navigation

To navigate to other component will use :

● From template using Router link on <a> tag with 2 ways :


○ <a class="nav-link" routerLink="/login">login</a>
○ <a [routerLink]="'/login'">Login</a> or
[routerLink]="['/login' , movie.id]"
Navigation

To navigate to other component will use :

● From .ts file using navigate :


○ import { Router } from '@angular/router';
○ Create instance from router service (private route:Router)
○ this.route.navigate(['/login']);
Navigation
● Add child routes to a parent one :
{ path: "artist/”,

children: [

{ path: "", component:ArtistTrackListComponent },

{ path: "music", component:MusicComponent}]

},

● Add general route for not found routes :


{path: '**', component:PageNotFoundComponent }
Navigation : routerLinkActive [ Self Study]

An important feature of any navigation component is giving the user feedback


about which menu item they are currently viewing. Another way to describe this is
giving the user feedback about which route is currently active.

It takes as input an array of classes which it will add to the element it’s attached to
if it’s route is currently active

<a class="nav-link" [routerLink]="['home']" [routerLinkActive]="['active']">Home </a>

Material : https://angular.io/api/router/RouterLinkActive
Navigation : Parameterised Routes

Sometimes we need part of the path in one or more of our routes (the URLs) to
be a variable, a common example of this is an ID for example : /movie/1

We will learn to :

● Configure parameterised routes in our route definition object.


● Components can be notified with what the parameter values are when the
URL gets visited.
● Have optional parameters in routes.
Navigation : Parameterised Routes

First we need to configure this id in routes array

const routes: Routes = [

{ path: movie/:id', component: MovieComponent}

];

The path has a variable called id, we know it’s a variable since it

begins with a colon :


Navigation : Parameterised Routes

To go to this parameterised route we will be from html or ts

From html :

[routerLink]="[‘movie’, movie.id]”

From ts:

this.router.navigate(['movie', idValue]);
Navigation : Parameterised Routes

To get this parameter in component will user ActivatedRoute

import {ActivatedRoute} from "@angular/router";

constructor(private route: ActivatedRoute) {

this.route.snapshot.params['id']

}
Dependency
Injection
Dependency Injection

● Dependency or dependent means relying on something for support ,


Dependencies are services or objects that a class needs to perform its
function. Dependency injection, or DI, is a design pattern in which a class
requests dependencies from external sources rather than creating them.

● You can use Angular DI to increase flexibility and modularity in your


applications.
Services

● A service is typically a class with a narrow, well-defined purpose. It should do


something specific and do it well. A component can delegate certain tasks to
services, such as fetching data from the server , In Angular, a class with the
@Injectable() decorator that encapsulates non-UI logic and code that can be
reused across an application.
● The @Injectable() metadata allows the service class to be used with the
dependency injection mechanism. The injectable class is instantiated by a
provider. Injectors maintain lists of providers and use them to provide service
instances when they are required by components or other services.
Why Services !

● Components shouldn't fetch or save data directly and they certainly


shouldn't knowingly present fake data. They should focus on presenting
data and delegate data access to a service.
● When you provide the service at the root level, Angular creates a single,
shared instance of this service and injects into any class that asks for it.
● Registering the provider in the @Injectable metadata also allows Angular
to optimize an application by removing the service if it turns out not to be
used after all.
Services
Services

To generate a new service :

● ng generate service service-name

By default the value is set to ‘root’. This translates to the root injector of the
application. Basically, setting the field to ‘root’ makes the service available
anywhere.
Observable

Observable is a stream of events or data , Subscribing "kicks off" the observable


stream. Without a subscribe (or an async pipe) the stream won't start emitting
values. It's similar to subscribing to a newspaper or magazine ... you won't start
getting them until you subscribe.
Subscribe

● A function that defines how to obtain or generate values or messages to


be published. This function is executed when a consumer calls the
subscribe() method of an observable.
● The subscribe() method takes a JavaScript object (called an observer) with
up to three callbacks, one for each type of notification that an observable
can deliver:
○ The Success notification sends a value such as a number, a string, or
an object.
○ The error notification sends a JavaScript Error or exception.
○ The complete notification doesn't send a value, but the handler is
called when the call completes. Scheduled values can continue to be
returned after the call completes.
Transfer data using services

● When passing data between components that lack a direct connection,


such as siblings, grandchildren, etc, you should create a shared service.
When you have data that should be sync, BehaviorSubject very useful in
this situation.

● BehaviorSubject holds data in a stream and to get data you need to


subscribe to get most recent data.

● We use .next() to update BehaviorSubject value that holds in our service.


Transfer data using services:

Behavior subject

In the service,

● we create a private BehaviorSubject that will hold the current value


of the message.
● We define a currentValue variable handle this data stream as an
observable that will be used by the components.
● Lastly, we create function that calls next on the BehaviorSubject to
change its value.
Transfer data using services:
Behavior subject
HTTP Request
Http Requests in Javascript
The XMLHttpRequest object can be used to exchange data with a server behind the
scenes. This means that it is possible to update parts of a web page, without
reloading the whole page.

var xhttp = new XMLHttpRequest();


xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText)
}
};
xhttp.open("GET", "API", true);
xhttp.send();
Http

● In your service that calls apis import httpClient and create a new instance from
it in constructor

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

getList(): Observable<any> {
return this.http.get('API');
}
Subscribe

● Import your service in component and create instance in constructor then


use this service methods
● Call the service in ngOnInit for API callings for example
https://angular.io/tutorial/toh-pt4#call-it-in-ngoninit

Example :

this.service.getData().subscribe(
data => { this.data = data },
error => { console.log('error: ', error)},
() => { console.log('complete ', "compelete"); });
Thank you
Lap
Products
Continuing on the previous task

● Navbar will contain


○ Products page route and will be the default when open the project
○ Route for login
○ Route for register
○ Route for cart
● Create a Not Found page
● Create a new route called cart
Products 5 Register Login

Shirt Shoes

Out of stock In stock In stock

Add to cart Add to cart Add to cart

Out of stock In stock Out of stock


Add to cart Add to cart Add to cart
Products App
As a user I would like to:
Show list of the products using http Modules instead of static array
Each product card item should have:

● Product images
● Product name
● Product category
● Product price [ 20 EGP]
● “Add to cart” button

Product card will be clickable to show detailed view for the item clicked
Products Products Register Login

● Create a product details component.


● When user click on any product card from the
list he should be redirected to details page with
the route

● Products List :

https://60523dc8fb49dc00175b7d04.mockapi.io/
api/v1/products Products details data
● Product Details :
Add to cart
https://60523dc8fb49dc00175b7d04.mockapi.io/
api/v1/products/id
Products 5 Register Login

Cart

Image name price Quantity

image prod 20EGP + 2 - remove

+ 1 - remove

+ 5 - remove

Total : 200 EGP


Products App
Also a user I would like to:
Redirect to cart page.
Shopping cart that shows count value of added and selected items
○ When user click on the cart icon show the following:
■ If counter = 0 : show in shopping cart page ( Empty cart )
■ If count > 0 : show items count in page
○ Show selected products in cart page with option to +/- item count and
remove items from cart
○ Show the total price for cart also at the bottom of the table.

You might also like