angular 模块构建_通过构建全栈应用程序学习Angular 6
angular 模塊構(gòu)建
Angular 6 is out! The new features include better performance, new powerful CLI additions and a new way to inject services.
Angular 6出來了! 新功能包括更好的性能,新的功能強大的CLI附加功能以及注入服務(wù)的新方法。
This tutorial is for beginners. You’ll learn Angular by example by building a full-stack CRUD — Create, Read, Update and Delete — web application. We will use the latest version of the most popular framework and platform for building mobile and desktop client-side applications. The name for these applications is SPAs or Single Page Applications.
本教程適用于初學(xué)者。 您將通過構(gòu)建完整的CRUD(創(chuàng)建,讀取,更新和刪除)Web應(yīng)用程序為例來學(xué)習(xí)Angular。 我們將使用最流行的框架和平臺的最新版本來構(gòu)建移動和桌面客戶端應(yīng)用程序。 這些應(yīng)用程序的名稱為SPA或單頁應(yīng)用程序。
In the back-end, we’ll use Python with Django. Django is the most popular pythonic web framework designed for perfectionists with deadlines.
在后端,我們將Python與Django結(jié)合使用。 Django是最受歡迎的pythonic Web框架,專為有期限的完美主義者而設(shè)計。
In nutshell, you’ll learn to generate Angular 6 apps, generate components and services, and add routing. You’ll also learn to use various features such as HttpClient for sending AJAX requests and HTTP calls and subscribing to RxJS 6 observables and so on.
簡而言之,您將學(xué)習(xí)生成Angular 6應(yīng)用程序,生成組件和服務(wù)以及添加路由。 您還將學(xué)習(xí)使用各種功能,例如HttpClient發(fā)送AJAX請求和HTTP調(diào)用以及訂閱RxJS 6 Observables等。
By the end of this Angular 6 tutorial, you’ll learn by building a real-world example application:
在Angular 6教程結(jié)束時,您將通過構(gòu)建真實的示例應(yīng)用程序來學(xué)習(xí):
- how to install the latest version of Angular CLI, 如何安裝最新版本的Angular CLI,
how to use the Angular 6 CLI to generate a new Angular 6 project,
如何使用Angular 6 CLI生成新的Angular 6項目,
- how to use Angular 6 to build a simple CRM application, 如何使用Angular 6構(gòu)建簡單的CRM應(yīng)用程序,
- what’s a component and component-based architecture 什么是基于組件和基于組件的架構(gòu)
how to use RxJS 6 Observables and operators (map() and filter() etc.)
如何使用RxJS 6 Observables和運算符( map()和filter()等)
- how to create Angular 6 components, 如何創(chuàng)建Angular 6組件,
- how to add component routing and navigation, 如何添加組件路由和導(dǎo)航,
how to use HttpClient to consume a REST API etc.
如何使用HttpClient消耗REST API等
Django示例CRUD后端 (The Django Example CRUD Back-End)
We’ll make use of a simple CRUD API built with Django and Django REST framework. Since this is an Angular tutorial we’ll not focus on building the API. That will be the subject of a separate tutorial. You can grab the source code of the back-end API from this repository.
我們將使用由Django和Django REST框架構(gòu)建的簡單CRUD API。 由于這是Angular教程,因此我們將不專注于構(gòu)建API。 這將是一個單獨的教程的主題。 您可以從此存儲庫中獲取后端API的源代碼。
You can use the following commands to start the development server:
您可以使用以下命令來啟動開發(fā)服務(wù)器:
# Clone the project and navigate into it$ git clone https://github.com/techiediaries/django-crm $ cd django-crm# Create a virtual environment and install packages$ pipenv install# Activate the virtual environment$ pipenv shell # Create and migrate the database then run the local development server$ python manage.py migrate $ python manage.py runserverYour server will be running from http://localhost:8000.
您的服務(wù)器將從http://localhost:8000 。
We are using pipenv, the officially recommended package management tool for Python. You’ll need to have it installed. The process is quite simple depending on your operating system.
我們正在使用pipenv ,這是Python官方推薦的軟件包管理工具。 您需要安裝它。 根據(jù)您的操作系統(tǒng),該過程非常簡單。
Angular 6 CRUD示例 (Angular 6 CRUD Example)
The example Angular 6 application we’ll be building is the front-end for a CRM RESTful API. It will allow you to create accounts, leads, opportunities, and contacts. It’s a perfect example for a CRUD (Create, Read, Update and Delete) application built as an SPA (Single Page Application).
我們將構(gòu)建的示例Angular 6應(yīng)用程序是CRM RESTful API的前端。 它將允許您創(chuàng)建客戶,潛在客戶,機會和聯(lián)系人。 這是構(gòu)建為SPA(單頁應(yīng)用程序)的CRUD(創(chuàng)建,讀取,更新和刪除)應(yīng)用程序的完美示例。
The example application is work in progress so we’ll be building it through a series of tutorials. It will be updated to contain advanced features such as RxJS 6 and JWT authentication. We’ll also use Bootstrap 4 and Angular 6 Material for building and styling the UI components. You either need Bootstrap 4 or Angular Material for styling. Depending on your choice you can follow separate tutorials:
該示例應(yīng)用程序正在開發(fā)中,因此我們將通過一系列教程進行構(gòu)建。 它將進行更新以包含高級功能,例如RxJS 6和JWT身份驗證。 我們還將使用Bootstrap 4和Angular 6 Material來構(gòu)建和樣式化UI組件。 您需要使用Bootstrap 4或Angular Material進行樣式設(shè)置。 根據(jù)您的選擇,您可以遵循單獨的教程:
Building the UI with Angular 6 Material
使用Angular 6材質(zhì)構(gòu)建UI
Building the UI with Bootstrap 4
使用Bootstrap 4構(gòu)建UI
安裝Angular CLI(v6.0.0) (Installing the Angular CLI (v6.0.0))
Make sure you have Node.js installed, then run the following command in your terminal to install Angular CLI v 6.0.0.
確保已安裝Node.js,然后在終端中運行以下命令以安裝Angular CLI v 6.0.0 。
npm -g install @angular/cliYou can check the installed version by running the following command:
您可以通過運行以下命令來檢查安裝的版本:
Now, you’re ready to create a project using Angular CLI v6. Simply run the following command in your terminal:
現(xiàn)在,您準(zhǔn)備使用Angular CLI v6創(chuàng)建一個項目。 只需在終端中運行以下命令:
The CLI will automatically generate a bunch of files common to most Angular 6 projects. It will also install the required dependencies for your project.
CLI將自動生成大多數(shù)Angular 6項目共有的一堆文件。 它還將為您的項目安裝所需的依賴項。
We will mostly be working inside the src/app folder. This is the directory structure of the project:
我們將主要在src/app文件夾內(nèi)工作。 這是項目的目錄結(jié)構(gòu):
You can serve your application locally by running the following commands:
您可以通過運行以下命令在本地為應(yīng)用程序提供服務(wù):
# Navigate inside your project's folder$ cd crmapp# Serve your application$ ng serveYour application will be running from http://localhost:4200.
您的應(yīng)用程序?qū)膆ttp://localhost:4200 。
This is a screen-shot of the home page of the application:
這是應(yīng)用程序主頁的屏幕截圖:
Angular 6 | 5 | 4中的組件 (Components in Angular 6|5|4)
Now, what’s a component?
現(xiàn)在,什么是組件?
A component is a TypeScript class. It has an HTML template and an optional set of CSS styles that control a part of the screen.
組件是TypeScript類。 它具有一個HTML模板和一組可選CSS樣式,用于控制屏幕的一部分。
Components are the most important concept in Angular 6. An Angular 6 application is basically a tree of components with a root component (the famous AppComponent). The root component is the one contained in the bootstrap array in the main NgModule module app.module.ts.
組件是Angular 6中最重要的概念。Angular 6應(yīng)用程序基本上是具有根組件(著名的AppComponent )的組件樹。 根組件是主NgModule模塊app.module.ts引導(dǎo)數(shù)組中NgModule組件。
One important aspect of components is re-usability. A component can be re-used throughout the application and even in other applications. Common and repeatable code that performs a certain task can be encapsulated into a reusable component. That component can be called whenever we need the functionality it provides.
組件的一個重要方面是可重用性。 組件可以在整個應(yīng)用程序中甚至在其他應(yīng)用程序中重復(fù)使用。 可以將執(zhí)行特定任務(wù)的通用和可重復(fù)代碼封裝到可重用的組件中。 只要我們需要它提供的功能,就可以調(diào)用該組件。
Each bootstrapped component is the base of its own tree of components. Inserting a bootstrapped component usually triggers a cascade of component creations that fill out that tree. Source
每個自舉組件都是其自己的組件樹的基礎(chǔ)。 插入自舉組件通常會觸發(fā)一系列創(chuàng)建該樹的組件。 資源
基于組件的架構(gòu) (Component-Based Architecture)
An Angular application is made of several components. These components form a tree structure with parent and child components.
Angular應(yīng)用程序由幾個組件組成。 這些組件與父組件和子組件形成樹結(jié)構(gòu)。
A component is an independent block of a big system (web application). It communicates with the other building blocks (components) of the system using inputs and outputs. A component has associated view, data, and behavior. It may have parent and child components.
組件是大系統(tǒng)(Web應(yīng)用程序)的獨立模塊。 它使用輸入和輸出與系統(tǒng)的其他構(gòu)建塊(組件)進行通信。 組件具有關(guān)聯(lián)的視圖,數(shù)據(jù)和行為。 它可能具有父組件和子組件。
Components allow maximum re-usability, easy testing, maintenance and separation of concerns.
組件可實現(xiàn)最大的可重用性,易于測試,維護和分離問題。
Let’s now see this practically. Head over to your Angular application project folder and open the src/app folder. You will find the following files:
現(xiàn)在讓我們實際來看一下。 轉(zhuǎn)到Angular應(yīng)用程序項目文件夾,然后打開src/app文件夾。 您將找到以下文件:
app.component.css: the CSS file for the component
app.component.css :組件CSS文件
app.component.html: the HTML view for the component
app.component.html :組件HTML視圖
app.component.spec.ts: the unit tests or spec file for the component
app.component.spec.ts :組件的單元測試或規(guī)范文件
app.component.ts: the component code (data and behavior)
app.component.ts :組件代碼(數(shù)據(jù)和行為)
app.module.ts: the application main module
app.module.ts :應(yīng)用程序主模塊
Except for the last file which contains the declaration of the application main (root) Module, all these files are used to create a component. It’s the AppComponent: The root component of our application. All other components we are going to create next will be direct or un-direct children of the root component.
除了包含應(yīng)用程序主(根) 模塊聲明的最后一個文件以外,所有這些文件都用于創(chuàng)建組件。 它是AppComponent :我們應(yīng)用程序的根組件。 接下來要創(chuàng)建的所有其他組件將是根組件的直接或非直接子代。
揭開AppComponent神秘面紗(Angular應(yīng)用程序的根組件) (Demystifying the AppComponent (The Root Component of Angular Applications))
Go ahead and open the src/app/app.component.ts file and let's understand the code behind the main/root component of the application.
繼續(xù)并打開src/app/app.component.ts文件,讓我們了解應(yīng)用程序主/根組件背后的代碼。
First, this is the code:
首先,這是代碼:
import { Component } from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'app';}We first import the Component decorator from @angular/core. Then we use it to decorate the TypeScript class AppComponent. The Component decorator takes an object with many parameters such as:
我們首先從@angular/core導(dǎo)入Component裝飾器。 然后,我們用它來裝飾TypeScript類AppComponent 。 組件裝飾器采用帶有許多參數(shù)的對象,例如:
selector: specifies the tag that can be used to call this component in HTML templates just like the standard HTML tags
選擇器 :指定可用于在HTML模板中調(diào)用此組件的標(biāo)簽,就像標(biāo)準(zhǔn)HTML標(biāo)簽一樣
templateUrl: indicates the path of the HTML template that will be used to display this component (you can also use the template parameter to include the template inline as a string)
templateUrl :指示將用于顯示此組件HTML模板的路徑(您也可以使用template參數(shù)將模板內(nèi)聯(lián)包含為字符串)
styleUrls: specifies an array of URLs for CSS style-sheets for the component
styleUrls :為組件CSS樣式表指定URL數(shù)組
The export keyword is used to export the component so that it can be imported from other components and modules in the application.
export關(guān)鍵字用于導(dǎo)出組件,以便可以從應(yīng)用程序中的其他組件和模塊導(dǎo)入它。
The title variable is a member variable that holds the string ‘a(chǎn)pp’. There is nothing special about this variable and it’s not a part of the canonical definition of an Angular component.
title變量是一個包含字符串“ app”的成員變量。 這個變量沒有什么特別的,它也不是Angular組件的規(guī)范定義的一部分。
Now let’s see the corresponding template for this component. If you open src/app/app.component.html this is what you'll find:
現(xiàn)在,讓我們看看該組件的相應(yīng)模板。 如果您打開src/app/app.component.html ,就會發(fā)現(xiàn):
<div style="text-align:center"><h1>Welcome to !</h1> <img width="300" alt="Angular Logo" src="data:image/svg+xml;...."></div> <h2>Here are some links to help you start: </h2><ul> <li> <h2><a target="_blank" rel="noopener" href="https://angular.io/tutorial">Tour of Heroes</a></h2> </li> <li> <h2><a target="_blank" rel="noopener" href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a></h2> </li> <li> <h2><a target="_blank" rel="noopener" href="https://blog.angular.io/">Angular blog</a></h2> </li></ul>The template is a normal HTML file (almost all HTML tags are valid to be used inside Angular templates except for some tags such as <script>, <html>; and <body> ) with the exception that it can contain template variables (in this case the title variable) or expressions ({ {...}}) that can be used to insert values in the DOM dynamically. This is called interpolation or data binding. You can find more information about templates from the docs.
模板是一個普通HTML文件(除<scri pt >, <h tml>和<body>之類的某些標(biāo)簽外,幾乎所有HTML標(biāo)簽都可以在Angular模板中使用),但它可以包含模板變量(在這種情況下為title變量) or exp表達(dá)式({{...}}),可用于在DOM動態(tài)庫y中插入值。 這可以進行 插值或數(shù)據(jù)綁定。 您可以從文檔中找到有關(guān)示例的更多信息。
You can also use other components directly inside Angular templates (via the selector property) just like normal HTML.
您也可以直接在Angular模板中使用其他組件(通過selector屬性),就像普通HTML一樣。
If you are familiar with the MVC (Model View Controller) pattern, the component class plays the role of the Controller. The HTML template plays the role of the View.
如果您熟悉MVC(模型視圖控制器)模式,則組件類將充當(dāng)控制器的角色。 HTML模板充當(dāng)視圖的角色。
Angular 6組件示例 (Angular 6 Components by Example)
After getting the theory behind Angular components, let’s now create the components for our simple CRM application.
在了解了Angular組件背后的理論之后,現(xiàn)在讓我們?yōu)楹唵蔚腃RM應(yīng)用程序創(chuàng)建組件。
Our REST API, built with Django, exposes these endpoints:
我們使用Django構(gòu)建的REST API公開了以下端點:
/api/accounts: create or read a paginated list of accounts
/api/accounts :創(chuàng)建或讀取分頁的帳戶列表
/api/accounts/<id>: read, update or delete an account
/api/accounts/< id>:讀取,更新或刪除帳戶
/api/contacts: create or read a paginated list of contacts
/api/contacts :創(chuàng)建或讀取分頁的聯(lián)系人列表
/api/contacts/<id>: read, update or delete a contact
/api/contacts/< id>:讀取,更新或刪除聯(lián)系人
/api/leads: create or read a paginated list of leads
/api/leads :創(chuàng)建或讀取分頁的潛在客戶列表
/api/leads/<id>: read, update or delete a lead
/api/leads/< id>:讀取,更新或刪除線索
/api/opportunities: create or read a paginated list of opportunities
/api/opportunities :創(chuàng)建或閱讀分頁的機會列表
/api/opportunities/<id>: read, update or delete an opportunity
/api/opportunities/< id>:讀取,更新或刪除機會
Before adding routing to our application we first need to create the application’s components. Based on the exposed REST API architecture we can divide our application into these components:
在向我們的應(yīng)用程序添加路由之前,我們首先需要創(chuàng)建應(yīng)用程序的組件。 基于公開的REST API體系結(jié)構(gòu),我們可以將應(yīng)用程序分為以下組件:
AccountListComponent: this component displays and controls a tabular list of accounts
AccountListComponent :此組件顯示和控制帳戶的表格列表
AccountCreateComponent: this component displays and controls a form for creating or updating accounts
AccountCreateComponent :此組件顯示和控制用于創(chuàng)建或更新帳戶的表單
ContactListComponent: displays a table of contacts
ContactListComponent :顯示聯(lián)系人表
ContactCreateComponent: displays a form to create or update a contact
ContactCreateComponent :顯示用于創(chuàng)建或更新聯(lián)系人的表單
LeadListComponent: displays a table of leads
LeadListComponent :顯示線索表
LeadCreateComponent: displays a form to create or update a lead
LeadCreateComponent :顯示用于創(chuàng)建或更新潛在客戶的表單
OpportunityListComponent: displays a table of opportunities
OpportunityListComponent :顯示機會表
OpportunityCreateComponent: displays a form to create or update an opportunity
OpportunityCreateComponent :顯示用于創(chuàng)建或更新機會的表單
Let’s use the Angular CLI to create the components
讓我們使用Angular CLI創(chuàng)建組件
ng generate component AccountList ng generate component AccountCreate ng generate component ContactList ng generate component ContactCreate ng generate component LeadList ng generate component LeadCreate ng generate component OpportunityList ng generate component OpportunityCreateThis is the output of the first command:
這是第一個命令的輸出:
CREATE src/app/account-list/account-list.component.css (0 bytes) CREATE src/app/account-list/account-list.component.html (31 bytes) CREATE src/app/account-list/account-list.component.spec.ts (664 bytes) CREATE src/app/account-list/account-list.component.ts (292 bytes) UPDATE src/app/app.module.ts (418 bytes)You can see that the command generates all the files to define a component and also updates src/app/app.module.ts.
您可以看到該命令生成了所有文件以定義組件,并且還更新了src/app/app.module.ts 。
If you open src/app/app.module.ts after running all commands, you can see that all components are automatically added to the AppModule declarations array.:
如果在運行所有命令后打開src/app/app.module.ts ,可以看到所有組件都自動添加到AppModule declarations數(shù)組中:
import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { AppComponent } from './app.component';import { AccountListComponent } from './account-list/account-list.component';import { AccountCreateComponent } from './account-create/account-create.component';import { ContactListComponent } from './contact-list/contact-list.component';import { ContactCreateComponent } from './contact-create/contact-create.component';import { LeadListComponent } from './lead-list/lead-list.component';import { LeadCreateComponent } from './lead-create/lead-create.component';import { OpportunityListComponent } from './opportunity-list/opportunity-list.component';import { OpportunityCreateComponent } from './opportunity-create/opportunity-create.component';@NgModule({declarations: [ AppComponent, AccountListComponent, AccountCreateComponent, ContactListComponent, ContactCreateComponent, LeadListComponent, LeadCreateComponent, OpportunityListComponent, OpportunityCreateComponent],imports: [ BrowserModule],providers: [],bootstrap: [AppComponent]})export class AppModule { }If you are creating components manually, you need to make sure to include them manually so they can be recognized as part of the module.
如果要手動創(chuàng)建組件,則需要確保手動包括它們,以便將它們識別為模塊的一部分。
添加Angular 6路由 (Adding Angular 6 Routing)
Angular CLI provides the --routing switch (ng new crmapp --routing) that enables you to add routing automatically. We’re going to add routing manually. I want you to understand the various pieces involved in adding component routing to your Angular application.
Angular CLI提供了--routing開關(guān)( ng new crmapp --routing ),使您可以自動添加路由。 我們將手動添加路由。 我希望您了解將組件路由添加到Angular應(yīng)用程序中涉及的各個部分。
In fact, adding routing is quite simple:
實際上,添加路由非常簡單:
add a separate module (which can be called AppRoutingModule) in a file app-routing.module.ts, and import the module by including it in the imports of main AppModule,
添加單獨的模塊(其可被稱為AppRoutingModule )在一個文件中app-routing.module.ts ,并且通過包括它在導(dǎo)入模塊imports主要的AppModule ,
add <router-outlet></router-outlet> in app.component.html (this is where the Angular Router will insert components matching the current path),
tlet> in app.co mponent.html中添加<router-outlet></route r-ou tlet> in app.co (這是Angular Router插入與當(dāng)前路徑匹配的組件的位置),
add routes (each route is an object with properties such as path and component etc.).
添加路線(每個路線都是具有諸如路徑和組件等屬性的對象)。
This is the initial content of app-routing.module.ts:
這是app-routing.module.ts的初始內(nèi)容:
import { NgModule } from '@angular/core';import { Routes, RouterModule } from '@angular/router';const routes: Routes = [];@NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule]})export class AppRoutingModule { }The routes will contain all the routes of the application. After creating the components we’ll see how to add routes to this array.
路由將包含應(yīng)用程序的所有路由。 創(chuàng)建組件之后,我們將看到如何向該數(shù)組添加路由。
For now, we want to redirect the visitor to the /accounts path when the home URL is visited so the first path we'll add is:
現(xiàn)在,我們想在訪問家庭URL時將訪問者重定向到/accounts路徑,因此我們要添加的第一個路徑是:
{ path: '', redirectTo: 'accounts', pathMatch: 'full' },The pathMatch specifies the matching strategy. full means that we want to fully match the path.
pathMatch指定匹配策略。 full表示我們要完全匹配路徑。
Next, let’s add the other paths:
接下來,讓我們添加其他路徑:
{ path: '', redirectTo: 'accounts', pathMatch: 'full' },{ path: 'accounts', component: AccountListComponent},{ path: 'create-account', component: AccountCreateComponent},{ path: 'contacts', component: ContactListComponent},{ path: 'create-contact', component: ContactCreateComponent},{ path: 'leads', component: LeadListComponent},{ path: 'create-lead', component: LeadCreateComponent},{ path: 'opportunities', component: OpportunityListComponent},{ path: 'create-opportunity', component: OpportunityCreateComponent}];Now open src/app/app.module.ts and import the routing module then add it to the imports array:
現(xiàn)在打開src/app/app.module.ts并導(dǎo)入路由模塊,然后將其添加到imports數(shù)組中:
import {AppRoutingModule} from './app-routing.module';[...]@NgModule({declarations: [AppComponent,[...]],imports: [ BrowserModule, AppRoutingModule],[...]})export class AppModule { }Finally, open src/app/app.component.html then add the navigation links and the router outlet:
最后,打開src/app/app.component.html然后添加導(dǎo)航鏈接和路由器出口:
<a [routerLink]="'/accounts'"> Accounts </a><a [routerLink]="'/create-account'"> Create Account </a><a [routerLink]="'/contacts'"> Contacts </a><a [routerLink]="'/create-contact'"> Create Contact </a><a [routerLink]="'/leads'"> Leads </a><a [routerLink]="'/create-lead'"> Create Lead </a><a [routerLink]="'/opportunities'"> Opportunities </a><a [routerLink]="'/create-opportunity'"> Create Opportunity </a><div> <router-outlet></router-outlet></div>使用Angular 6 HttpClient消耗REST API的示例 (An Example for Consuming the REST API Using Angular 6 HttpClient)
Now we’ve created the different components and added routing and navigation. Let’s see an example of how to use the HttpClient of Angular 6 to consume the RESTful API back-end.
現(xiàn)在,我們創(chuàng)建了不同的組件,并添加了路由和導(dǎo)航。 讓我們看一個如何使用Angular 6的HttpClient來使用RESTful API后端的示例。
First, you need to add the HttpClientModule module to the imports array of the main application module:
首先,您需要將HttpClientModule模塊添加到主應(yīng)用程序模塊的imports數(shù)組中:
[..]import { HttpClientModule } from '@angular/common/http';@NgModule({declarations: [..],imports: [[..]HttpClientModule],providers: [],bootstrap: [AppComponent]})export class AppModule { }創(chuàng)建一個Angular 6服務(wù)/提供者 (Create an Angular 6 Service/Provider)
A service is a global class that can be injected into any component. It’s used to encapsulate code that can be common between multiple components in one place instead of repeating it throughout various components.
服務(wù)是可以注入任何組件的全局類。 它用于封裝可以在一個地方的多個組件之間通用的代碼,而不是在各個組件中重復(fù)執(zhí)行。
Now, let's create a service that encapsulates all the code needed for interacting with the REST API. Using Angular CLI run the following command:
現(xiàn)在,讓我們創(chuàng)建一個服務(wù),該服務(wù)封裝與REST API交互所需的所有代碼。 使用Angular CLI運行以下命令:
Two files: src/app/api.service.ts and src/app/api.service.spec.ts will be generated. The first contains code for the service and the second contains tests.
將生成兩個文件: src/app/api.service.ts和src/app/api.service.spec.ts 。 第一個包含服務(wù)的代碼,第二個包含測試。
Open src/app/api.service.ts then import and inject the HttpClient class.
打開src/app/api.service.ts然后導(dǎo)入并注入HttpClient類。
import { Injectable } from '@angular/core';import { HttpClient} from '@angular/common/http';@Injectable({providedIn: 'root'})export class APIService { constructor(private httpClient: HttpClient) {}}Angular 6 provides a way to register services/providers directly in the @Injectable() decorator by using the new providedIn attribute. This attribute accepts any module of your application or 'root' for the main app module. Now you don't have to include your service in the providers array of your module.
角6提供了一種注冊服務(wù)/供應(yīng)商直接在@Injectable()通過使用新的裝飾providedIn屬性。 此屬性接受應(yīng)用程序的任何模塊或主應(yīng)用程序模塊的'root' 。 現(xiàn)在,您不必將服務(wù)包含在模塊的providers數(shù)組中。
獲取聯(lián)系人/發(fā)送HTTP GET請求示例 (Getting Contacts/Sending HTTP GET Request Example)
Let’s start with the contacts API endpoint.
讓我們從通訊錄API端點開始。
- First, we’ll add a method to consume this endpoint in our global API service, 首先,我們將在我們的全局API服務(wù)中添加使用此端點的方法,
next, we’ll inject the API service and call the method from the corresponding component class (ContactListComponent)
接下來,我們將注入API服務(wù)并從相應(yīng)的組件類( ContactListComponent )中調(diào)用方法
- and finally, we’ll display the result (the list of contacts) in the component template. 最后,我們將在組件模板中顯示結(jié)果(聯(lián)系人列表)。
Open src/app/api.service.ts and add the following method:
打開src/app/api.service.ts并添加以下方法:
export class APIService {API_URL = 'http://localhost:8000';constructor(private httpClient: HttpClient) {}getContacts(){ return this.httpClient.get(`${this.API_URL}/contacts`);}Next, open src/app/contact-list/contact-list.component.ts and inject the APIService then call the getContacts() method:
接下來,打開src/app/contact-list/contact-list.component.ts并注入APIService,然后調(diào)用getContacts()方法:
import { Component, OnInit } from '@angular/core';import { APIService } from '../api.service';@Component({ selector: 'app-contact-list', templateUrl: './contact-list.component.html', styleUrls: ['./contact-list.component.css']})export class ContactListComponent implements OnInit {private contacts: Array<object> = [];constructor(private apiService: APIService) { }ngOnInit() { this.getContacts();}public getContacts(){ this.apiService.getContacts().subscribe((data: Array<object>) => { this.contacts = data; console.log(data); });}Now let’s display the contacts in the template. Open src/app/contact-list/contact-list.component.html and add the following code:
現(xiàn)在,讓我們在模板中顯示聯(lián)系人。 打開src/app/contact-list/contact-list.component.html并添加以下代碼:
<h1>My Contacts</h1><div><table style="width:100%"><tr> <th>First Name</th> <th>Last Name</th> <th>Phone</th> <th>Email</th> <th>Address</th></tr><tr *ngFor="let contact of contacts"> <td> {{ contact.first_name }}</td> <td> {{ contact.last_name }} </td> <td> {{ contact.phone }}</td> <td> {{ contact.email }} </td> <td> {{ contact.address }}</td></tr></table></div>This is a screen-shot of the component:
這是該組件的屏幕截圖:
創(chuàng)建聯(lián)系人/發(fā)送HTTP POST請求示例 (Creating Contacts/Sending HTTP POST Request Example)
Now let’s create a method to send HTTP Post request to create a random contact. Open the API service file and add the following method:
現(xiàn)在,讓我們創(chuàng)建一個發(fā)送HTTP Post請求以創(chuàng)建隨機聯(lián)系人的方法。 打開API服務(wù)文件并添加以下方法:
createContact(contact){ return this.httpClient.post(`${this.API_URL}/contacts/`,contact);}Next, let’s call this method from the ContactCreateComponent to create a contact. First, open src/app/contact-create/contact-create.component.ts and add the following code:
接下來,讓我們從ContactCreateComponent調(diào)用此方法以創(chuàng)建聯(lián)系人。 首先,打開src/app/contact-create/contact-create.component.ts并添加以下代碼:
import { Component, OnInit } from '@angular/core';import { APIService } from '../api.service';@Component({selector: 'app-contact-create',templateUrl: './contact-create.component.html',styleUrls: ['./contact-create.component.css']})export class ContactCreateComponent implements OnInit {constructor(private apiService: APIService) { }ngOnInit() {}createContact(){var contact = { account: 1, address: "Home N 333 Apartment 300", createdBy: 1, description: "This is the third contact", email: "abbess@email.com", first_name: "kaya", isActive: true, last_name: "Abbes", phone: "00121212101"};this.apiService.createContact(contact).subscribe((response) => { console.log(response);});};}}For now, we’re simply hard-coding the contact info for the sake of simplicity.
現(xiàn)在,為簡單起見,我們僅對聯(lián)系信息進行硬編碼。
Next, open src/app/contact-create/contact-create.component.html and add a button to call the method to create a contact:
接下來,打開src/app/contact-create/contact-create.component.html并添加一個按鈕以調(diào)用該方法來創(chuàng)建聯(lián)系人:
<h1> Create Contact </h1> <button (click)="createContact()"> Create Contact </button>結(jié)論 (Conclusion)
Throughout this Angular 6 tutorial for beginners, we’ve seen, by building a simple real-world CRUD example, how to use different Angular concepts to create simple full-stack CRUD application with Angular and Django. You can find the source code in this repository.
在面向初學(xué)者的整個Angular 6教程中,我們通過構(gòu)建一個簡單的真實CRUD示例,了解了如何使用不同的Angular概念通過Angular和Django創(chuàng)建簡單的全棧CRUD應(yīng)用程序。 您可以在此存儲庫中找到源代碼。
翻譯自: https://www.freecodecamp.org/news/learn-angular-6-by-building-a-full-stack-application-186659f51a27/
angular 模塊構(gòu)建
總結(jié)
以上是生活随笔為你收集整理的angular 模块构建_通过构建全栈应用程序学习Angular 6的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到买新房子在装修什么意思
- 下一篇: hacktoberfest_我第一次参加