0% found this document useful (0 votes)
10 views28 pages

MPTpr18a1_merged

The document outlines the steps to implement lazy loading in an Angular application for customer and sales order data, enhancing loading efficiency by only loading necessary components on demand. It includes detailed commands for generating modules and components, updating their configurations, and setting up a data service for fetching data. Additionally, it explains the concept of CORS and provides a guide for creating a component to make CORS requests to an API, ensuring proper handling of cross-origin requests.
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)
10 views28 pages

MPTpr18a1_merged

The document outlines the steps to implement lazy loading in an Angular application for customer and sales order data, enhancing loading efficiency by only loading necessary components on demand. It includes detailed commands for generating modules and components, updating their configurations, and setting up a data service for fetching data. Additionally, it explains the concept of CORS and provides a guide for creating a component to make CORS requests to an API, ensuring proper handling of cross-origin requests.
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
You are on page 1/ 28

OUTPUTS:

Modern Practical Tools(4340705) 20______

-:Practical 19:-

Aim: Design a page to load customer and Sales order data using lazy loading
technique in angular.

Lazy loading is a technique used in Angular to optimize the loading time of large applications
by loading only the necessary components and modules when they are required, rather than
loading everything upfront.

In a typical Angular application, all the components and modules are loaded when the
application is first launched. This can slow down the initial loading time of the application,
especially if the application is large and contains many components and modules. With lazy
loading, the application can be divided into smaller feature modules, each of which is loaded
only when the user navigates to the corresponding route.

Step 1: Generate the customer module: Run the following command in your terminal to
generate a new module for customers:

ng generate module customers

Step 2: Update customer module as below:

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


import { CommonModule } from '@angular/common';
import { CustomersRoutingModule } from './customers-routing.module';
import { CustomerListComponent } from './customer-list/customer-list.component';

@NgModule({
declarations: [
CustomerListComponent
],
imports: [
CommonModule,
CustomersRoutingModule
]
})
export class CustomersModule { }

Step 3: Generate the customer list component: Run the following command in your
terminal to generate a new component for displaying the customer list:

ng generate component customers/customer-list

Compiled by: AHH Page


Modern Practical Tools(4340705) 20______

Step 4: Update customer-list.component.ts as below for loading the customer data:

import { Component, OnInit } from '@angular/core';


import { DataService } from '../../data.service';

@Component({
selector: 'app-customer-list',
templateUrl: './customer-list.component.html',
styleUrls: ['./customer-list.component.css']
})
export class CustomerListComponent implements OnInit {
customers: any[] = [];
isLoading = false;

constructor(private dataService: DataService) { }

ngOnInit() {
this.loadCustomers();
}

loadCustomers() {
this.isLoading = true;
this.dataService.getCustomers().subscribe((customers: any[]) => {
this.customers = customers;
this.isLoading = false;
});
}
}

Step 5: In the customer-list.component.html file, display the customer data:

<div *ngIf="isLoading">
Loading customers...
</div>
<div *ngIf="!isLoading">
<h2>Customers</h2>
<ul>
<li *ngFor="let customer of customers">{{ customer.name }}</li>
</ul>
</div>

Compiled by: AHH Page


Modern Practical Tools(4340705) 20______

Step 5: Generate the sales module: Run the following command in your terminal to
generate a new module for sales:

ng generate module sales

Step 6: Update sales module as below:

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


import { CommonModule } from '@angular/common';
import { SalesRoutingModule } from './sales-routing.module';
import { SalesOrderListComponent } from './sales-order-list/sales-order-list.component';

@NgModule({
declarations: [
SalesOrderListComponent
],
imports: [
CommonModule,
SalesRoutingModule
]
})
export class SalesModule { }

Step 7: Generate the sales order list component: Run the following command in your
terminal to generate a new component for displaying the sales order list:

ng generate component sales/sales-order-list

Step 8: Update sales-order-list.component.ts as below for loading the customer data:

import { Component, OnInit } from '@angular/core';


import { DataService } from '../../data.service';

@Component({
selector: 'app-sales-order-list',
templateUrl: './sales-order-list.component.html',
styleUrls: ['./sales-order-list.component.css']
})
export class SalesOrderListComponent implements OnInit {
salesOrders: any[] = [];
isLoading = false;
Compiled by: AHH Page
Modern Practical Tools(4340705) 20______

constructor(private dataService: DataService) { }

ngOnInit() {
this.loadSalesOrders();
}

loadSalesOrders() {
this.isLoading = true;
this.dataService.getSalesOrders().subscribe((salesOrders: any[]) => {
this.salesOrders = salesOrders;
this.isLoading = false;
});
}
}

Step 9: In the sales-order-list.component.html file, display the customer data:

<div *ngIf="isLoading">
Loading sales orders...
</div>
<div *ngIf="!isLoading">
<h2>Sales Orders</h2>
<ul>
<li *ngFor="let order of salesOrders">{{ order.orderNumber }}</li>
</ul>
</div>

Step 10: Create a data service to fetch the customer and sales order data: Run the
following command in your terminal to create a new service:

ng generate service data

Step 11: This will create a new file called data.service.ts in the src/app directory. Replace
its content with the following code:

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


import { Observable, of } from 'rxjs';

@Injectable({

Compiled by: AHH Page


Modern Practical Tools(4340705) 20______

providedIn: 'root'
})
export class DataService {
getCustomers(): Observable<any[]> {
// Replace with the actual logic to fetch customer data
return of([
{ id: 1, name: 'Janak' },
{ id: 2, name: 'Rekha' },
{ id: 3, name: 'Mayank' },
{ id: 4, name: 'Pratibha' },
{ id: 5, name: 'Vinayak' }
]);
}

getSalesOrders(): Observable<any[]> {
// Replace with the actual logic to fetch sales order data
return of([
{ orderNumber: 'SO-001', total: 100 },
{ orderNumber: 'SO-002', total: 200 },
{ orderNumber: 'SO-003', total: 300 },
{ orderNumber: 'SO-004', total: 400 },
{ orderNumber: 'SO-005', total: 500 }
]);
}
}

Step 12: Update the routing configuration to enable lazy loading: Open the app-
routing.module.ts file and update it as follows:

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


import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [


{ path: 'customers', loadChildren: () => import('./customers/customers.module').then(m
=> m.CustomersModule) },
{ path: 'sales', loadChildren: () => import('./sales/sales.module').then(m =>
m.SalesModule) },
{ path: '', redirectTo: '/sales', pathMatch: 'full' },
{ path: '**', redirectTo: '/customers' }
];
Compiled by: AHH Page
Modern Practical Tools(4340705) 20______

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

Step 13: Open the app.component.html file and replace its content with the following
line:

<router-outlet></router-outlet>

Compiled by: AHH Page


PRACTICAL19
OUTPUTS
Modern Practical Tools(4340705) 20______

-:Practical 20:-

Aim: Design a page to implement CORS concept.

CORS stands for Cross-Origin Resource Sharing. It is a security feature implemented in


modern web browsers that restricts web pages from making requests to a different domain
or origin than the one that served the web page.

In the context of Angular, CORS is an important concept to understand because when Angular
applications communicate with APIs hosted on a different domain, CORS needs to be enabled
on the API server-side to allow the Angular application to make requests to the API.

Angular applications typically use the HttpClient module to make HTTP requests to APIs.
When a request is made to a different domain or origin, the browser will automatically send
a preflight OPTIONS request to the API to check if the requested domain or origin is allowed
to make requests to the API. If CORS is not enabled on the API server-side to allow requests
from the Angular application, the API server will respond with an error and the request will
fail.

To enable CORS on the API server-side, the API must respond with specific headers that allow
the requesting domain or origin to access the API. These headers include Access-Control-
Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers,
among others.

In summary, CORS is an important concept to understand when building Angular


applications that communicate with APIs hosted on a different domain or origin. It is
necessary to ensure that CORS is enabled on the API server-side to allow the Angular
application to make requests to the API.

Step 1: Create a new component: Run the following command in your terminal to create
a new component:

ng g c cors-example

Step 2: In the cors-example.component.ts file, define the logic for making a CORS request:

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


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

@Component({
selector: 'app-cors-example',
templateUrl: './cors-example.component.html',
styleUrls: ['./cors-example.component.css']
})
Compiled by: AHH Page
Modern Practical Tools(4340705) 20______

export class CorsExampleComponent {


responseData: any;
errorMessage!: string;

constructor(private http: HttpClient) { }

makeCorsRequest() {
const url = 'http://localhost:3000/products'; // Replace with the desired API endpoint

this.http.get(url).subscribe(
(response) => {
this.responseData = response;
this.errorMessage = "";
},
(error) => {
this.responseData = null;
this.errorMessage = error.message;
}
);
}
}

Step 3: In the cors-example.component.html file, add a button to trigger the CORS request
and display the response:

<div>
<button (click)="makeCorsRequest()">Make CORS Request</button>
</div>
<div *ngIf="responseData">
<pre>{{ responseData | json }}</pre>
</div>
<div *ngIf="errorMessage">
<p>Error: {{ errorMessage }}</p>
</div>

Step 4: Open the app.module.ts file and update it with the following code

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


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

Compiled by: AHH Page


Modern Practical Tools(4340705) 20______

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


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

import { AppComponent } from './app.component';


import { CorsExampleComponent } from './cors-example/cors-example.component';

@NgModule({
declarations: [
AppComponent,
CorsExampleComponent
],
imports: [
BrowserModule,
AppRoutingModule,HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Step5: Open the app.component.html file and replace its content with the following line:

<app-cors-example></app-cors-example>

Compiled by: AHH Page


PRACTICAL20
OUTPUTS

You might also like