1677264600
了解如何使用 Angular 和 NestJS 構建 Web 應用程序。使用 Angular 和 NestJS 構建一個項目。使用 Angular 和 NestJS 創建你自己的項目
使用 Angular 和 NestJS 構建項目是創建健壯的全棧 Web 應用程序的好方法。Angular 是一種流行的前端 JavaScript 框架,它提供了一套完整的功能來構建豐富的交互式用戶界面。相比之下,使用 Node.js 構建的後端框架 NestJS 提供了一組強大的工具來構建高效且可擴展的服務器端應用程序。
這兩個框架共同為構建現代 Web 應用程序提供了完整的解決方案,從前端用戶界面到服務器端后端邏輯。在本教程中,我們將學習如何使用 Angular 和 NestJS 構建項目,包括設置開發環境、創建組件和服務、處理路由以及進行 API 調用。
本教程將使您全面了解如何使用 Angular 和 NestJS 構建 Web 應用程序。閱讀本文後,您將能夠使用這個強大的堆棧創建自己的項目。
目錄:
要開始使用本教程,請確保您具備以下條件:
NestJS 和 Angular 都是基於 JavaScript 並使用 JavaScript 作為主要編程語言的 Web 應用程序框架。這兩個框架還具有以下特點:
但是,存在一些差異:
NestJS 和 Angular 在全棧 Web 開發中可以很好地互補。他們可以一起創建具有強大後端和動態交互式前端的完整 Web 應用程序。
要設置 NestJS 項目,您需要先安裝 NestJS CLI 工具,如下所示:
npm i -g @nestjs/cli
接下來,通過使用您選擇的項目名稱運行以下命令來創建一個新項目。對於本教程,我們使用tasks作為項目名稱:
nest new tasks
此命令將提示您選擇要為您的項目管理的包。例如,您可以在 npm 和 Yarn 之間進行選擇。對於本教程,我們將使用 npm。選擇了首選的包管理器後,將安裝項目的依賴項。
現在,導航到項目目錄並運行開發服務器:
cd tasks
npm run start:dev
開發服務器運行後,您應該會看到“Hello World!” 通過在瀏覽器中導航到http://localhost:3000來發送消息。
現在您的 NestJS 項目已設置,您可以為應用程序的前端創建一個新的 Angular 項目。
通過在終端中運行以下命令來安裝 Angular CLI:
npm install -g @angular/cli
接下來,通過使用您選擇的項目名稱運行以下命令來創建一個新項目。對於此演示,我們使用tasks-ui作為項目名稱:
ng tasks-ui
現在導航到項目目錄並安裝項目依賴項:
cd tasks-ui
npm install
<
最後使用如下命令運行開發:
ng serve
開發服務器運行後,您應該能夠通過在瀏覽器中導航到http://localhost:4200來查看默認的 Angular 應用程序。
現在您已經設置了後端和前端服務器,是時候創建任務應用程序來保存和顯示您的日常任務列表了。
首先,您將創建後端 API。這將包括創建路由、控制器和服務來處理任務數據,以及 CRUD 操作。
tasks.json首先在項目的根目錄中創建一個文件。該文件將作為一個數據庫來存儲您的任務記錄。
接下來,src/app.service.ts使用以下代碼更新文件:
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;
}
}
此代碼實現了一項服務,允許您管理任務列表。該服務利用該@nestjs/common模塊為 NestJS 提供裝飾器和實用功能,並利用該fs模塊與文件系統進行交互。
ATasks interface被定義為構建服務將管理的每個任務對象。裝飾@Injectable()器用於使AppService類可注入。
私有屬性tasks被定義為保存一個對像數組,並通過從文件中讀取任務並將其解析為一個 Tasks 對像數組來在構造函數中Tasks進行初始化。tasks.json該服務具有三種方法:
NestJS 中的控制器負責處理傳入的 HTTP 請求並返回適當的響應。它充當客戶端和服務之間的中介,接收來自客戶端的輸入,對其進行處理,然後返迴響應。
要為應用程序創建控制器,您需要定義處理不同請求的路由和方法。這將允許我們的應用程序處理各種類型的客戶端請求,例如 GET、POST、PUT 和 DELETE。
要為 創建控制器,請使用以下代碼AppService更新文件:src/app.controllers.ts
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);
}
}
}
此代碼定義了一個控制器,用於處理 NestJS 應用程序中與任務相關的請求。控制器使用@Controller裝飾器進行裝飾,裝飾器是從@nestjs/common.
裝飾器接受一個字符串參數,它定義了控制器的端點。在這種情況下,端點是api/tasks。該代碼還導入了其他裝飾器,例如@Get、@Post、 @ Body、@Delete和 ,@Param用於處理不同類型的請求並從請求中提取數據。
被AppService導入是因為它是一個依賴項,用於處理應用程序的邏輯。控制器具有三個方法:getTasks()、createTask()和deleteTask()。
每個方法都使用與其處理的 HTTP 請求類型相對應的裝飾器進行裝飾。該getTasks()方法裝飾有並通過調用的方法@Get()返回任務列表。getTasks()AppService
該createTasks()方法用@Post()和裝飾@Body()。createTask()它通過調用的方法AppService並傳入任務名稱來創建新任務。
該deleteTask()方法用@Delete()和裝飾@Param()。它通過調用deleteTask()的方法AppService並傳入任務來刪除任務id。
這些方法還包括使用 try-catch 塊進行錯誤處理,並在發生錯誤時拋出一個HttpExceptionwith 。HttpStatus.INTERNAL_SERVER_ERROR
現在任務 API 已完成,您已成功構建應用程序的後端部分!
現在是時候使用 Angular 創建應用程序的 UI,然後使用 API 從用戶界面管理任務了。
首先,使用以下命令生成任務的服務:
ng generate service tasks
此命令在目錄中使用服務名稱創建一個新的服務文件src/app,並將其註冊到app.module.ts 文件中。
接下來,使用下面的代碼片段更新tasks.service.ts文件以添加使用 NestJS API 的服務:
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}`);
}
}
上面的代碼在 Angular 中定義了一個服務來處理與功能相關的任務。該服務使用@Injectable裝飾器進行裝飾,該裝飾器是從@angular/core.
該服務有一個host屬性,用於保存後端 API 的基本 URL。此外,HttpClient導入該模塊以向後端發出 HTTP 請求。
該服務具有三種方法:getTasks()、addTask()和deleteTask()。該getTasks()方法向後端發出 GET 請求以檢索任務。該addTask()方法向後端發出 POST 請求以添加新任務。該deleteTask()方法向後端發出 DELETE 請求以刪除特定任務。
每個方法使用HttpClient模塊向後端發出相應的 HTTP 請求並返迴響應。操作map員從可觀察接口中提取響應。
接下來,使用以下代碼更新app.components.ts文件以訂閱您剛剛創建的服務:
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);
});
}
}
上面的代碼定義了一個AppComponent類。是AppComponent用@Componentdecorator 裝飾的,它是從@angular/core. 它具有selector、templateUrl和styleUrls屬性,分別用於指定組件的選擇器、模板和样式。
被TaskService導入並註入到組件的構造函數中。
該組件具有三個屬性:
該方法在組件初始化ngOnInit()時調用。TaskService該組件具有三個方法:
讓我們利用 中定義的方法和變量來AppComponent顯示從 API 返回的任務並附加事件處理程序以提交表單以添加新任務和刪除現有任務。
app.component.html使用以下代碼更新文件:
<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>
此代碼是模板的一部分AppComponent。它包括一個輸入字段、一個按鈕和一個無序列表。輸入字段使用指令綁定到task組件的屬性ngModel。
輸入字段的值雙向綁定到屬性task,因此當用戶在輸入字段中鍵入內容時,屬性的值task會更新,而當屬性的值task更新時,輸入字段也會更新。
按鈕元素有一個圖標和一個addTask()使用(click)事件綁定到組件方法的事件。當用戶單擊此圖標時,addTask()將使用任務文本調用該方法。
tasks無序列表使用指令遍歷數組ngFor。該指令為數組中的每個任務創建一個新的列表項元素tasks,並將任務數據綁定到task變量。每個列表項元素都顯示任務名稱並有一個垃圾桶圖標,該圖標帶有事件綁定到deleteTask()使用該(click)事件的組件的方法。當用戶單擊垃圾桶圖標時,deleteTask()將使用任務調用該方法id。
src/styles.css要增強應用程序的外觀,請使用以下樣式表更新文件中的樣式:
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;
}
上面的樣式表將設置輸入字段的樣式並將添加 (+) 按鈕放置在字段旁邊。它還會按行格式化任務,並在每個任務項旁邊添加一個刪除(垃圾桶)圖標。
現在是時候驗證您的應用程序是否正常運行了。在運行應用程序之前,您需要啟用代理以防止 CORS(跨源資源共享)問題。代理充當中間人,處理來自試圖從其他服務器訪問資源的客戶端的請求。這可以提高網絡性能、安全性和合規性。
要啟用代理,請proxy.config.json在您的src目錄中創建一個名為的文件並添加以下配置:
{
"/api": {
"target": "http://localhost:3000",
"secure": false,
"pathRewrite": {"^/api" : ""}
}
}
現在運行後端和前端開發服務器,並導航到http://localhost:4200/預覽前端:
您可以通過單擊+圖標添加更多任務,並通過單擊垃圾桶圖標刪除任務。
在本教程中,我們介紹瞭如何使用 Angular 和 NestJS 構建項目。我們首先解釋了這兩個框架之間的相似之處。然後,我們為 NestJS 和 Angular 設置開發服務器。接下來,我們創建了一個將數據寫入 JSON 文件的 NestJS 服務,作為應用程序的數據庫。然後我們實現了一個 Angular 服務,該服務將 API 請求發送到 NestJS 後端以執行 CRUD 操作。
最後,我們更新了 Angular App 組件類以創建允許從 App 模板進行數據操作的方法。現在您已經了解瞭如何在構建全棧應用程序時集成 Angular 和 NestJS,您可以在下一個項目中使用這些框架。您還可以通過從 GitHub克隆完整項目來更新後端以使用實際數據庫,如 MongoDB 或 MySQL 。
我希望本教程對您有所幫助,並為您在下一個項目中使用 Angular 和 NestJS 提供了一些想法。編碼愉快!
資料來源: 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
1598940617
Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.
In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!
For Installing Angular on your Machine, there are 2 prerequisites:
First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js
Download and Install Node.js version suitable for your machine’s operating system.
Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:
· After executing the command, Angular CLI will get installed within some time. You can check it using the following command
Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:
To create a workspace:
#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli
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
1627043546
The term web design simply encompasses a design process related to the front-end design of website that includes writing mark-up. Creative web design has a considerable impact on your perceived business credibility and quality. It taps onto the broader scopes of web development services.
Web designing is identified as a critical factor for the success of websites and eCommerce. The internet has completely changed the way businesses and brands operate. Web design and web development go hand-in-hand and the need for a professional web design and development company, offering a blend of creative designs and user-centric elements at an affordable rate, is growing at a significant rate.
In this blog, we have focused on the different areas of designing a website that covers all the trends, tools, and techniques coming up with time.
Web design
In 2020 itself, the number of smartphone users across the globe stands at 6.95 billion, with experts suggesting a high rise of 17.75 billion by 2024. On the other hand, the percentage of Gen Z web and internet users worldwide is up to 98%. This is not just a huge market but a ginormous one to boost your business and grow your presence online.
Web Design History
At a huge particle physics laboratory, CERN in Switzerland, the son of computer scientist Barner Lee published the first-ever website on August 6, 1991. He is not only the first web designer but also the creator of HTML (HyperText Markup Language). The worldwide web persisted and after two years, the world’s first search engine was born. This was just the beginning.
Evolution of Web Design over the years
With the release of the Internet web browser and Windows 95 in 1995, most trading companies at that time saw innumerable possibilities of instant worldwide information and public sharing of websites to increase their sales. This led to the prospect of eCommerce and worldwide group communications.
The next few years saw a soaring launch of the now-so-famous websites such as Yahoo, Amazon, eBay, Google, and substantially more. In 2004, by the time Facebook was launched, there were more than 50 million websites online.
Then came the era of Google, the ruler of all search engines introducing us to search engine optimization (SEO) and businesses sought their ways to improve their ranks. The world turned more towards mobile web experiences and responsive mobile-friendly web designs became requisite.
Let’s take a deep look at the evolution of illustrious brands to have a profound understanding of web design.
Here is a retrospection of a few widely acclaimed brands over the years.
Netflix
From a simple idea of renting DVDs online to a multi-billion-dollar business, saying that Netflix has come a long way is an understatement. A company that has sent shockwaves across Hollywood in the form of content delivery. Abundantly, Netflix (NFLX) is responsible for the rise in streaming services across 190 countries and meaningful changes in the entertainment industry.
1997-2000
The idea of Netflix was born when Reed Hastings and Marc Randolph decided to rent DVDs by mail. With 925 titles and a pay-per-rental model, Netflix.com debuts the first DVD rental and sales site with all novel features. It offered unlimited rentals without due dates or monthly rental limitations with a personalized movie recommendation system.
Netflix 1997-2000
2001-2005
Announcing its initial public offering (IPO) under the NASDAQ ticker NFLX, Netflix reached over 1 million subscribers in the United States by introducing a profile feature in their influential website design along with a free trial allowing members to create lists and rate their favorite movies. The user experience was quite engaging with the categorization of content, recommendations based on history, search engine, and a queue of movies to watch.
Netflix 2001-2005 -2003
2006-2010
They then unleashed streaming and partnering with electronic brands such as blu-ray, Xbox, and set-top boxes so that users can watch series and films straight away. Later in 2010, they also launched their sophisticated website on mobile devices with its iconic red and black themed background.
Netflix 2006-2010 -2007
2011-2015
In 2013, an eye-tracking test revealed that the users didn’t focus on the details of the movie or show in the existing interface and were perplexed with the flow of information. Hence, the professional web designers simply shifted the text from the right side to the top of the screen. With Daredevil, an audio description feature was also launched for the visually impaired ones.
Netflix 2011-2015
2016-2020
These years, Netflix came with a plethora of new features for their modern website design such as AutoPay, snippets of trailers, recommendations categorized by genre, percentage based on user experience, upcoming shows, top 10 lists, etc. These web application features yielded better results in visual hierarchy and flow of information across the website.
Netflix 2016-2020
2021
With a sleek logo in their iconic red N, timeless black background with a ‘Watch anywhere, Cancel anytime’ the color, the combination, the statement, and the leading ott platform for top video streaming service Netflix has overgrown into a revolutionary lifestyle of Netflix and Chill.
Netflix 2021
Contunue to read: Evolution in Web Design: A Case Study of 25 Years
#web #web-design #web-design-development #web-design-case-study #web-design-history #web-development