1677220295
Learn how to use Angular and NestJS to build a web application. Build a project using Angular and NestJS. Create your own projects using Angular and NestJS
Building a project using Angular and NestJS is a great way to create a robust, full-stack web application. Angular, a popular frontend JavaScript framework, offers a complete set of features for building rich, interactive user interfaces. In contrast, NestJS, a backend framework built with Node.js, provides a robust set of tools for building efficient and scalable server-side applications.
Together, these two frameworks provide a complete solution for building modern web applications, from the frontend user interface to the server-side backend logic. In this tutorial, we will learn how to use Angular and NestJS to build a project, including setting up the development environment, creating components and services, handling routing, and making API calls.
This tutorial will provide you with a comprehensive understanding of how to use Angular and NestJS to build web applications. After reading this article, you’ll be able to create your own projects using this powerful stack.
Table of contents:
To get started with this tutorial, ensure you have the following:
NestJS and Angular are both web application frameworks that are based on JavaScript and use JavaScript as their primary programming language. Both frameworks also share the following features:
However, there are some differences:
NestJS and Angular complement each other well in full-stack web development. Together, they can create a complete web application with a robust backend and a dynamic, interactive frontend.
To set up a NestJS project, you’ll need to first install the NestJS CLI tool, like so:
npm i -g @nestjs/cli
Next, create a new project by running the following command with the project name of your choice. For this tutorial, we’re using tasks
as the project name:
nest new tasks
This command will prompt you to choose the package to manage for your project. For example, you can select between npm and Yarn. For this tutorial, we’ll use npm. Once you’ve selected your preferred package manager, the project’s dependencies will be installed.
Now, navigate to the project directory and run the development server:
cd tasks
npm run start:dev
Once the development server is running, you should see a “Hello World!” message by navigating to http://localhost:3000 in your browser.
Now that your NestJS project is set up, you can create a new Angular project for the application’s frontend.
Start by installing the Angular CLI by running the following command in your terminal:
npm install -g @angular/cli
Next, create a new project by running the following command with the project name of your choice. For this demonstration, we’re using tasks-ui
as the project name:
ng
tasks-ui
Now navigate to the project directory and install the project dependencies:
cd tasks-ui
npm install
<
Finally, use the following command to run the development:
ng serve
Once the development server is running, you should be able to see the default Angular application by navigating to http://localhost:4200 in your browser.
Now that you’ve both the backend and frontend servers set up, it’s time to create the task application to save and display your list of daily tasks.
To begin, you’ll create the backend APIs. This will include creating routes, controllers, and services to handle the task data, as well as the CRUD operations.
Start by creating a tasks.json
file in the root directory of your project. This file will serve as a database to store your task records.
Next, update the src/app.service.ts
file with the following code:
import { Injectable } from '@nestjs/common';
import * as fs from 'fs';
export interface Tasks {
id: number;
name: string;
completed: boolean;
}
@Injectable()
export class AppService {
private tasks: Array<Tasks>;
constructor() {
this.tasks = JSON.parse(fs.readFileSync('tasks.json', 'utf8'));
}
getTasks(): Tasks[] {
return this.tasks;
}
createTask(name: string): Tasks[] {
const task = { id: this.tasks.length + 1, name, completed: false };
this.tasks = [...this.tasks, { ...task}];
fs.writeFileSync('tasks.json', JSON.stringify(this.tasks));
return this.tasks;
}
deleteTask(id: number): Tasks[] {
const index = this.tasks.findIndex((task) => task.id === id);
this.tasks.splice(index, 1);
return this.tasks;
}
}
This code implements a service that allows you to manage a list of tasks. The service utilizes the @nestjs/common
module to provide decorators and utility functions for NestJS and the fs
module to interact with the file system.
A Tasks
interface
is defined to structure each task object the service will manage. The @Injectable()
decorator is used to make the AppService
class injectable.
A private property, tasks
, is defined to hold an array of Tasks
objects and is initialized in the constructor by reading the tasks from the tasks.json
file and parsing it into an array of Tasks objects. The service has three methods:
getTasks()
: Returns the current list of taskscreateTask(name: string)
: Creates a new task
object with a given name, adds it to the list of tasks, and then writes the updated list to the tasks.json
filedeleteTask(id: number)
: Deletes a task from the list based on the given id
The controller in NestJS is responsible for handling incoming HTTP requests and returning the appropriate response. It acts as an intermediary between the client and the service, receiving input from the client, processing it, and then returning a response.
To create a controller for the application, you’ll need to define the routes and methods for handling different requests. This will allow our application to handle various types of client requests such as GET, POST, PUT, and DELETE.
To create controllers for the AppService
, update the src/app.controllers.ts
file with the following code:
import {
Controller,
Get,
Post,
Body,
Delete,
Param,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { AppService } from './app.service';
import { Tasks } from './app.service';
@Controller('api/todos')
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getTodos(): Tasks[] {
try {
return this.appService.getTasks();
} catch (error) {
throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Post()
createTodo(@Body() { name }: Tasks): Tasks[] {
try {
return this.appService.createTask(name);
} catch (error) {
throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Delete(':id')
deleteTodo(@Param('id') id: number): Tasks[] {
try {
return this.appService.deleteTask(id);
} catch (error) {
throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
This code defines a controller for handling tasks related requests in a NestJS application. The controller is decorated with the @Controller
decorator, which is imported from @nestjs/common
.
The decorator takes in a string argument, which defines the endpoint for the controller. In this case, the endpoint is api/tasks
. The code also imports other decorators such as @Get
, @Post
, @Body
, @Delete
, and @Param
which are used to handle different types of requests and extract data from the request.
The AppService
is imported because it is a dependency and is used to handle the application’s logic. The controller has three methods: getTasks()
, createTask()
, and deleteTask()
.
Each method is decorated with a decorator corresponding to the type of HTTP request it handles. The getTasks()
method is decorated with @Get()
and returns a list of tasks by calling the getTasks()
method of the AppService
.
The createTasks()
method is decorated with @Post()
and @Body()
. It creates a new task by calling the createTask()
method of the AppService
and passing in the name of the task.
The deleteTask()
method is decorated with @Delete()
and @Param()
. It deletes a task by calling the deleteTask()
method of the AppService
and passing in the task id
.
The methods also include error handling by using try-catch blocks and throwing a HttpException
with HttpStatus.INTERNAL_SERVER_ERROR
when an error occurs.
Now that the task API is complete, you’ve successfully finished building the backend part of the application!
Now it’s time to create the application‘s UI using Angular and then consume the API to manage tasks from the user interface.
First, generate the service of a task with the following command:
ng generate service tasks
This command creates a new service file in the src/app
directory with the name of the service and also registers it in the app.module.t
s file.
Next, update tasks.service.ts
file with code snippets below to add the services to consume the NestJS APIs:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class TaskService {
host = 'http://localhost:3000/api';
// eslint-disable-next-line @typescript-eslint/no-empty-function
constructor(private http: HttpClient) {}
getTasks() {
return this.http.get(`${this.host}/tasks`).pipe(map((res) => res));
}
addTask(todo: string) {
return this.http.post(`${this.host}/tasks`, {
name: todo,
completed: false,
});
}
deleteTask(id: number) {
return this.http.delete(`${this.host}/tasks/${id}`);
}
}
The above code defines a service in Angular for handling functionality-related tasks. The service is decorated with the @Injectable
decorator, which is imported from @angular/core
.
The service has a host
property that holds the base URL of the backend API. In addition, the HttpClient
module is imported to make HTTP requests to the backend.
The service has three methods: getTasks()
, addTask()
, and deleteTask()
. The getTasks()
method makes a GET request to the backend to retrieve the tasks. The addTask()
method makes a POST request to the backend to add a new task. The deleteTask()
method makes a DELETE request to the backend to delete a specific task.
Each method uses the HttpClient
module to make the corresponding HTTP request to the backend and returns the response. The map
operator extracts the response from the observable interface.
Next, update the app.components.ts
file with the following code to subscribe to the service that you just created:
import { Component } from '@angular/core';
import { TaskService } from './todo.service';
interface Task {
id: number;
name: string;
completed: boolean;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
tasks: Task[];
task: string;
// eslint-disable-next-line @typescript-eslint/no-empty-function
constructor(
private taskService: TaskService,
) {
this.tasks = [];
this.task = '';
}
title = 'task-ui';
ngOnInit() {
this.taskService.getTasks().subscribe((data) => {
console.log(data);
this.tasks = data as Task[];
});
}
addTask(task: string) {
this.taskService.addTask(task).subscribe();
this.task ='';
}
deleteTask(id: number) {
this.taskService.deleteTask(id).subscribe((data) => {
console.log(data);
});
}
}
The above code defines an AppComponent
class. The AppComponent
is decorated with the @Component
decorator, which is imported from @angular/core
. It has a selector
, templateUrl
, and styleUrls
properties that are used to specify the component’s selector, template, and styles, respectively.
The TaskService
is imported and injected into the component’s constructor.
The component has three properties:
tasks
: Array of Task
objectstask
: Used to store the task that the user wants to addtitle
: Used to store the title of the applicationThe ngOnInit()
method is called when the TaskService
component is initialized. This component has three methods:
getTasks()
: Called to retrieve the tasks from the backendaddTask()
: Called when the user wants to add a new task to the backenddeleteTask()
: Called when the user wants to delete a task from the backendLet’s take advantage of the methods and variables defined in the AppComponent
to display the tasks returned from the API and to attach event handlers to submit a form to add a new task and to delete an existing task.
Update the app.component.html
file with the following code:
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css"
rel= "stylesheet"
/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.3/angular.min.js"></script>
<title>Document</title>
</head>
<body>
<div class="main" ng-app="mytodo" ng-controller="myCtrl">
<h1>Todo List App</h1>
<div class="search">
<input type="text" [(ngModel)]="task" />
<span (click)="addTask(task)"><i class="fas fa-plus"></i></span>
</div>
<ul>
<li *ngFor= "let task of tasks">
{{ task.name
}}<i class="fas fa-trash-alt" (click)="deleteTask(task.id)"></i>
</li>
</ul>
<p></p>
</div>
</body>
</html>
This code is a part of the AppComponent
template. It includes an input field, a button, and an unordered list. The input field is bound to the task
property of the component using the ngModel
directive.
The value of the input field is two-way bound to the task
property, so when the user types into the input field, the value of the task
property updates, and when the value of the task
property is updated, the input field updates.
The button element has an icon and an event binding to the addTask()
component method using the (click)
event. When a user clicks on this icon, the addTask()
method is called with the task text.
The unordered list iterates over the tasks
array using the ngFor
directive. This directive creates a new list item element for each task in the tasks
array and binds the task data to the task
variable. Each list item element displays the task name and has a trash icon with an event binding to the deleteTask()
method of the component using the (click)
event. When a user clicks on the trash icon, the deleteTask()
method is called with the task id
.
To enhance the appearance of your application, update the styles in the src/styles.css
file with the following stylesheets:
body{
justify-content: center;
display: flex;
font-family: 'Poppins', sans-serif;
}
.main{
width: 500px;
padding: 15p;
background-color: #ededed ;
}
h1{
text-align: center;
color: #e69d17;
margin: 10px;
}
input[type=text]{
width: 90%;
padding: 10px;
font-size: 16px;
margin-left: 8px;
border-radius: 3px;
border: none;
outline: none;
}
.search {
position: relative;
}
.search span{
position: absolute;
top: -10px;
right: -4px;
background: #e69d17;
padding: 20px;
display: flex;
border-radius: 50%;
width: 15px;
height: 15px;
cursor: pointer;
}
.search span i{
line-height: -100%;
}
ul {
padding: 2px;
list-style: none;
}
ul li {
background-color: #fff;
margin: 5px;
padding: 10px;
border-right: 4px solid #e69d17;
border-left: 4px solid #e69d17;
}
ul li i {
padding: 4px;
float: right;
cursor: pointer;
}
p{
color: red;
text-align: center;
}
The above stylesheet will style the input fields and position the add (+) button next to the fields. It will also format the tasks in rows and add a delete (trash) icon beside each task item.
Now it’s time to verify that your application is functioning correctly. Before running the application, you’ll need to enable a proxy to prevent CORS (Cross-Origin Resource Sharing) issues. A proxy acts as a middleman for requests from clients trying to access resources from other servers. This can improve network performance, security, and compliance.
To enable a proxy, create a file named proxy.config.json
in your src
directory and add the following configurations:
{
"/api": {
"target": "http://localhost:3000",
"secure": false,
"pathRewrite": {"^/api" : ""}
}
}
Now run the backend and frontend development servers, and navigate to http://localhost:4200/ to preview the frontend:
You can add more tasks by clicking on the + icon, and delete a task by clicking on the trash icon.
In this tutorial, we walked through how to build a project using Angular and NestJS. We began by explaining the similarities between the two frameworks. Then, we set up development servers for NestJS and Angular. Next, we created a NestJS service that wrote data to a JSON file, serving as the application’s database. We then implemented an Angular service that sent API requests to the NestJS backend to perform CRUD operations.
Finally, we updated the Angular App component class to create methods allowing data manipulation from the App template. Now that you have learned how to integrate Angular and NestJS in building a full-stack application, you can use these frameworks in your next project. You can also update the backend to use an actual database like MongoDB or MySQL by cloning the full project from GitHub.
I hope you found this tutorial helpful and gave you some ideas on using Angular and NestJS in your next project. Happy coding!
Source: https://blog.logrocket.com
#angular #nest
1621426329
AppClues Infotech is one of the leading Enterprise Angular Web Apps Development Company in USA. Our dedicated & highly experienced Angular app developers build top-grade Angular apps for your business with immersive technology & superior functionalities.
For more info:
Website: https://www.appcluesinfotech.com/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910
#top enterprise angular web apps development company in usa #enterprise angular web apps development #hire enterprise angular web apps developers #best enterprise angular web app services #custom enterprise angular web apps solution #professional enterprise angular web apps developers
1595344320
Corona Virus Pandemic has brought the world to a standstill.
Countries are on a major lockdown. Schools, colleges, theatres, gym, clubs, and all other public places are shut down, the country’s economy is suffering, human health is on stake, people are losing their jobs and nobody knows how worse it can get.
Since most of the places are on lockdown, and you are working from home or have enough time to nourish your skills, then you should use this time wisely! We always complain that we want some ‘time’ to learn and upgrade our knowledge but don’t get it due to our ‘busy schedules’. So, now is the time to make a ‘list of skills’ and learn and upgrade your skills at home!
And for the technology-loving people like us, Knoldus Techhub has already helped us a lot in doing it in a short span of time!
If you are still not aware of it, don’t worry as Georgia Byng has well said,
“No time is better than the present”
– Georgia Byng, a British children’s writer, illustrator, actress and film producer.
No matter if you are a developer (be it front-end or back-end) or a data scientist, tester, or a DevOps person, or, a learner who has a keen interest in technology, Knoldus Techhub has brought it all for you under one common roof.
From technologies like Scala, spark, elastic-search to angular, go, machine learning, it has a total of 20 technologies with some recently added ones i.e. DAML, test automation, snowflake, and ionic.
Every technology in Tech-hub has n number of templates. Once you click on any specific technology you’ll be able to see all the templates of that technology. Since these templates are downloadable, you need to provide your email to get the template downloadable link in your mail.
These templates helps you learn the practical implementation of a topic with so much of ease. Using these templates you can learn and kick-start your development in no time.
Apart from your learning, there are some out of the box templates, that can help provide the solution to your business problem that has all the basic dependencies/ implementations already plugged in. Tech hub names these templates as xlr8rs (pronounced as accelerators).
xlr8rs make your development real fast by just adding your core business logic to the template.
If you are looking for a template that’s not available, you can also request a template may be for learning or requesting for a solution to your business problem and tech-hub will connect with you to provide you the solution. Isn’t this helpful 🙂
To keep you updated, the Knoldus tech hub provides you with the information on the most trending technology and the most downloaded templates at present. This you’ll be informed and learn the one that’s most trending.
Since we believe:
“There’s always a scope of improvement“
If you still feel like it isn’t helping you in learning and development, you can provide your feedback in the feedback section in the bottom right corner of the website.
#ai #akka #akka-http #akka-streams #amazon ec2 #angular 6 #angular 9 #angular material #apache flink #apache kafka #apache spark #api testing #artificial intelligence #aws #aws services #big data and fast data #blockchain #css #daml #devops #elasticsearch #flink #functional programming #future #grpc #html #hybrid application development #ionic framework #java #java11 #kubernetes #lagom #microservices #ml # ai and data engineering #mlflow #mlops #mobile development #mongodb #non-blocking #nosql #play #play 2.4.x #play framework #python #react #reactive application #reactive architecture #reactive programming #rust #scala #scalatest #slick #software #spark #spring boot #sql #streaming #tech blogs #testing #user interface (ui) #web #web application #web designing #angular #coronavirus #daml #development #devops #elasticsearch #golang #ionic #java #kafka #knoldus #lagom #learn #machine learning #ml #pandemic #play framework #scala #skills #snowflake #spark streaming #techhub #technology #test automation #time management #upgrade
1611492348
Angular framework is built using TypeScript language that helps to ensures higher security. Angular is the most preferred framework for building reactive single page web applications and creative components of the website.
Want to get a unique front-end UI for your web application? Contact Skenix Infotech to know more about our Services & pricing: https://www.skenix.com/angular-web-app-development/
#angular development company #web app development #web application #hire angular developers #web services #angular framework
1627274472
Web app represents the particular firm or organization for which it is developed. With the help of a web app, the firm owner can promote and increase their business by reaching more and more customers for their website or web app.
Every firm or organization must have its own web app to represent their company, what they do, what they provide users feedback, and a lot more. If you have your web app then users can know your company deeply and they can also show interest in your company.
To develop a unique web app contact Nevina Infotech that is the best web application development services provider company, that can help you to develop the web app for your firm as per your requirement.
#web application development company #web application development services #web app development company #custom web application development company #web app development services #web application development agency
1626154510
A web app is a type of app that can help you to represent your business. A web app is everything you need for your company’s growth because you can promote your business with its help. With its use, you can show the customers what products you have and come to know about your firm.
You can hire Nevina Infotech to develop your web app for your business. We are the most famous company for developing web apps because we also provide web application development services. We have a great team to work with to build your web app.
#web application development company #web application development services #web app development company #custom web application development company #web app development services #web application development agency