angular 模塊構建
Angular 6 is out! The new features include better performance, new powerful CLI additions and a new way to inject services.
Angular 6出來了! 新功能包括更好的性能,新的功能強大的CLI附加功能以及注入服務的新方法。
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.
本教程適用于初學者。 您將通過構建完整的CRUD(創建,讀取,更新和刪除)Web應用程序為例來學習Angular。 我們將使用最流行的框架和平臺的最新版本來構建移動和桌面客戶端應用程序。 這些應用程序的名稱為SPA或單頁應用程序。
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結合使用。 Django是最受歡迎的pythonic Web框架,專為有期限的完美主義者而設計。
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.
簡而言之,您將學習生成Angular 6應用程序,生成組件和服務以及添加路由。 您還將學習使用各種功能,例如HttpClient發送AJAX請求和HTTP調用以及訂閱RxJS 6 Observables等。
By the end of this Angular 6 tutorial, you’ll learn by building a real-world example application:
在Angular 6教程結束時,您將通過構建真實的示例應用程序來學習:
- 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構建簡單的CRM應用程序,
- what’s a component and component-based architecture 什么是基于組件和基于組件的架構
how to use RxJS 6 Observables and operators (
map()
andfilter()
etc.)如何使用RxJS 6 Observables和運算符(
map()
和filter()
等)- how to create Angular 6 components, 如何創建Angular 6組件,
- how to add component routing and navigation, 如何添加組件路由和導航,
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框架構建的簡單CRUD API。 由于這是Angular教程,因此我們將不專注于構建API。 這將是一個單獨的教程的主題。 您可以從此存儲庫中獲取后端API的源代碼。
You can use the following commands to start the development server:
您可以使用以下命令來啟動開發服務器:
# 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 runserver
Your server will be running from http://localhost:8000
.
您的服務器將從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官方推薦的軟件包管理工具。 您需要安裝它。 根據您的操作系統,該過程非常簡單。
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).
我們將構建的示例Angular 6應用程序是CRM RESTful API的前端。 它將允許您創建客戶,潛在客戶,機會和聯系人。 這是構建為SPA(單頁應用程序)的CRUD(創建,讀取,更新和刪除)應用程序的完美示例。
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:
該示例應用程序正在開發中,因此我們將通過一系列教程進行構建。 它將進行更新以包含高級功能,例如RxJS 6和JWT身份驗證。 我們還將使用Bootstrap 4和Angular 6 Material來構建和樣式化UI組件。 您需要使用Bootstrap 4或Angular Material進行樣式設置。 根據您的選擇,您可以遵循單獨的教程:
Building the UI with Angular 6 Material
使用Angular 6材質構建UI
Building the UI with Bootstrap 4
使用Bootstrap 4構建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/cli
You 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:
現在,您準備使用Angular CLI v6創建一個項目。 只需在終端中運行以下命令:
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將自動生成大多數Angular 6項目共有的一堆文件。 它還將為您的項目安裝所需的依賴項。
We will mostly be working inside the src/app
folder. This is the directory structure of the project:
我們將主要在src/app
文件夾內工作。 這是項目的目錄結構:
You can serve your application locally by running the following commands:
您可以通過運行以下命令在本地為應用程序提供服務:
# Navigate inside your project's folder$ cd crmapp# Serve your application$ ng serve
Your application will be running from http://localhost:4200
.
您的應用程序將從http://localhost:4200
。
This is a screen-shot of the home page of the application:
這是應用程序主頁的屏幕截圖:
Angular 6 | 5 | 4中的組件 (Components in Angular 6|5|4)
Now, what’s a component?
現在,什么是組件?
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應用程序基本上是具有根組件(著名的AppComponent )的組件樹。 根組件是主NgModule
模塊app.module.ts
引導數組中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.
組件的一個重要方面是可重用性。 組件可以在整個應用程序中甚至在其他應用程序中重復使用。 可以將執行特定任務的通用和可重復代碼封裝到可重用的組件中。 只要我們需要它提供的功能,就可以調用該組件。
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
每個自舉組件都是其自己的組件樹的基礎。 插入自舉組件通常會觸發一系列創建該樹的組件。 資源
基于組件的架構 (Component-Based Architecture)
An Angular application is made of several components. These components form a tree structure with parent and child components.
Angular應用程序由幾個組件組成。 這些組件與父組件和子組件形成樹結構。
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.
組件是大系統(Web應用程序)的獨立模塊。 它使用輸入和輸出與系統的其他構建塊(組件)進行通信。 組件具有關聯的視圖,數據和行為。 它可能具有父組件和子組件。
Components allow maximum re-usability, easy testing, maintenance and separation of concerns.
組件可實現最大的可重用性,易于測試,維護和分離問題。
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:
現在讓我們實際來看一下。 轉到Angular應用程序項目文件夾,然后打開src/app
文件夾。 您將找到以下文件:
app.component.css
: the CSS file for the componentapp.component.css
:組件CSS文件app.component.html
: the HTML view for the componentapp.component.html
:組件HTML視圖app.component.spec.ts
: the unit tests or spec file for the componentapp.component.spec.ts
:組件的單元測試或規范文件app.component.ts
: the component code (data and behavior)app.component.ts
:組件代碼(數據和行為)app.module.ts
: the application main moduleapp.module.ts
:應用程序主模塊
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.
除了包含應用程序主(根) 模塊聲明的最后一個文件以外,所有這些文件都用于創建組件。 它是AppComponent :我們應用程序的根組件。 接下來要創建的所有其他組件將是根組件的直接或非直接子代。
揭開AppComponent神秘面紗(Angular應用程序的根組件) (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.
繼續并打開src/app/app.component.ts
文件,讓我們了解應用程序主/根組件背后的代碼。
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
導入Component裝飾器。 然后,我們用它來裝飾TypeScript類AppComponent 。 組件裝飾器采用帶有許多參數的對象,例如:
selector: specifies the tag that can be used to call this component in HTML templates just like the standard HTML tags
選擇器 :指定可用于在HTML模板中調用此組件的標簽,就像標準HTML標簽一樣
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參數將模板內聯包含為字符串)
styleUrls: specifies an array of URLs for CSS style-sheets for the component
styleUrls :為組件CSS樣式表指定URL數組
The export keyword is used to export the component so that it can be imported from other components and modules in the application.
export關鍵字用于導出組件,以便可以從應用程序中的其他組件和模塊導入它。
The title variable is a member variable that holds the string ‘app’. There is nothing special about this variable and it’s not a part of the canonical definition of an Angular component.
title變量是一個包含字符串“ app”的成員變量。 這個變量沒有什么特別的,它也不是Angular組件的規范定義的一部分。
Now let’s see the corresponding template for this component. If you open src/app/app.component.html
this is what you'll find:
現在,讓我們看看該組件的相應模板。 如果您打開src/app/app.component.html
,就會發現:
<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 <scri
pt>,
<html>
; and <body> ) with the exception that it can contain template variables (in this case the title variable) or exp
ressions ({ {...}}) 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>之類的某些標簽外,幾乎所有HTML標簽都可以在Angular模板中使用),但它可以包含模板變量(在這種情況下為title變量) or exp
表達式({{...}}),可用于在DOM動態庫y中插入值。 這可以進行 插值或數據綁定。 您可以從文檔中找到有關示例的更多信息。
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(模型視圖控制器)模式,則組件類將充當控制器的角色。 HTML模板充當視圖的角色。
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組件背后的理論之后,現在讓我們為簡單的CRM應用程序創建組件。
Our REST API, built with Django, exposes these endpoints:
我們使用Django構建的REST API公開了以下端點:
/api/accounts
: create or read a paginated list of accounts/api/accounts
:創建或讀取分頁的帳戶列表/api/accounts/<
id>: read, update or delete an account/api/accounts/<
id>:讀取,更新或刪除帳戶/api/contacts
: create or read a paginated list of contacts/api/contacts
:創建或讀取分頁的聯系人列表/api/contacts/<
id>: read, update or delete a contact/api/contacts/<
id>:讀取,更新或刪除聯系人/api/leads
: create or read a paginated list of leads/api/leads
:創建或讀取分頁的潛在客戶列表/api/leads/<
id>: read, update or delete a lead/api/leads/<
id>:讀取,更新或刪除線索/api/opportunities
: create or read a paginated list of opportunities/api/opportunities
:創建或閱讀分頁的機會列表/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:
在向我們的應用程序添加路由之前,我們首先需要創建應用程序的組件。 基于公開的REST API體系結構,我們可以將應用程序分為以下組件:
AccountListComponent
: this component displays and controls a tabular list of accountsAccountListComponent
:此組件顯示和控制帳戶的表格列表AccountCreateComponent
: this component displays and controls a form for creating or updating accountsAccountCreateComponent
:此組件顯示和控制用于創建或更新帳戶的表單ContactListComponent
: displays a table of contactsContactListComponent
:顯示聯系人表ContactCreateComponent
: displays a form to create or update a contactContactCreateComponent
:顯示用于創建或更新聯系人的表單LeadListComponent
: displays a table of leadsLeadListComponent
:顯示線索表LeadCreateComponent
: displays a form to create or update a leadLeadCreateComponent
:顯示用于創建或更新潛在客戶的表單OpportunityListComponent
: displays a table of opportunitiesOpportunityListComponent
:顯示機會表OpportunityCreateComponent
: displays a form to create or update an opportunityOpportunityCreateComponent
:顯示用于創建或更新機會的表單
Let’s use the Angular CLI to create the components
讓我們使用Angular CLI創建組件
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 OpportunityCreate
This 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
數組中:
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.
如果要手動創建組件,則需要確保手動包括它們,以便將它們識別為模塊的一部分。
添加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
開關( ng new crmapp --routing
),使您可以自動添加路由。 我們將手動添加路由。 我希望您了解將組件路由添加到Angular應用程序中涉及的各個部分。
In fact, adding routing is quite simple:
實際上,添加路由非常簡單:
add a separate module (which can be called
AppRoutingModule
) in a fileapp-routing.module.ts
, and import the module by including it in theimports
of mainAppModule
,添加單獨的模塊(其可被稱為
AppRoutingModule
)在一個文件中app-routing.module.ts
,并且通過包括它在導入模塊imports
主要的AppModule
,add
<router-outlet></route
r-outlet> in app.co
mponent.html (this is where the Angular Router will insert components matching the current path),tlet> in app.co
mponent.html中添加<router-outlet></route
r-outlet> in app.co
(這是Angular Router插入與當前路徑匹配的組件的位置),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
的初始內容:
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.
路由將包含應用程序的所有路由。 創建組件之后,我們將看到如何向該數組添加路由。
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:
現在,我們想在訪問家庭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:
現在打開src/app/app.module.ts
并導入路由模塊,然后將其添加到imports數組中:
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
然后添加導航鏈接和路由器出口:
<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.
現在,我們創建了不同的組件,并添加了路由和導航。 讓我們看一個如何使用Angular 6的HttpClient來使用RESTful API后端的示例。
First, you need to add the HttpClientModule module to the imports array of the main application module:
首先,您需要將HttpClientModule模塊添加到主應用程序模塊的imports數組中:
[..]import { HttpClientModule } from '@angular/common/http';@NgModule({declarations: [..],imports: [[..]HttpClientModule],providers: [],bootstrap: [AppComponent]})export class AppModule { }
創建一個Angular 6服務/提供者 (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.
服務是可以注入任何組件的全局類。 它用于封裝可以在一個地方的多個組件之間通用的代碼,而不是在各個組件中重復執行。
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:
現在,讓我們創建一個服務,該服務封裝與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
。 第一個包含服務的代碼,第二個包含測試。
Open src/app/api.service.ts
then import and inject the HttpClient class.
打開src/app/api.service.ts
然后導入并注入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提供了一種注冊服務/供應商直接在@Injectable()
通過使用新的裝飾providedIn
屬性。 此屬性接受應用程序的任何模塊或主應用程序模塊的'root'
。 現在,您不必將服務包含在模塊的providers數組中。
獲取聯系人/發送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服務中添加使用此端點的方法,
next, we’ll inject the API service and call the method from the corresponding component class (
ContactListComponent
)接下來,我們將注入API服務并從相應的組件類(
ContactListComponent
)中調用方法- and finally, we’ll display the result (the list of contacts) in the component template. 最后,我們將在組件模板中顯示結果(聯系人列表)。
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,然后調用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:
現在,讓我們在模板中顯示聯系人。 打開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:
這是該組件的屏幕截圖:
創建聯系人/發送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:
現在,讓我們創建一個發送HTTP Post請求以創建隨機聯系人的方法。 打開API服務文件并添加以下方法:
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
調用此方法以創建聯系人。 首先,打開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.
現在,為簡單起見,我們僅對聯系信息進行硬編碼。
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
并添加一個按鈕以調用該方法來創建聯系人:
<h1> Create Contact </h1> <button (click)="createContact()"> Create Contact </button>
結論 (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.
在面向初學者的整個Angular 6教程中,我們通過構建一個簡單的真實CRUD示例,了解了如何使用不同的Angular概念通過Angular和Django創建簡單的全棧CRUD應用程序。 您可以在此存儲庫中找到源代碼。
翻譯自: https://www.freecodecamp.org/news/learn-angular-6-by-building-a-full-stack-application-186659f51a27/
angular 模塊構建