angular 模塊構建_通過構建全棧應用程序學習Angular 6

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() and filter() 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 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 :組件的單元測試或規范文件

  • app.component.ts: the component code (data and behavior)

    app.component.ts :組件代碼(數據和行為)

  • app.module.ts: the application main module

    app.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&gt;    <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&lt;/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>之類的某些標簽外,幾乎所有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 accounts

    AccountListComponent :此組件顯示和控制帳戶的表格列表

  • AccountCreateComponent: this component displays and controls a form for creating or updating accounts

    AccountCreateComponent :此組件顯示和控制用于創建或更新帳戶的表單

  • ContactListComponent: displays a table of contacts

    ContactListComponent :顯示聯系人表

  • ContactCreateComponent: displays a form to create or update a contact

    ContactCreateComponent :顯示用于創建或更新聯系人的表單

  • LeadListComponent: displays a table of leads

    LeadListComponent :顯示線索表

  • LeadCreateComponent: displays a form to create or update a lead

    LeadCreateComponent :顯示用于創建或更新潛在客戶的表單

  • OpportunityListComponent: displays a table of opportunities

    OpportunityListComponent :顯示機會表

  • OpportunityCreateComponent: displays a form to create or update an opportunity

    OpportunityCreateComponent :顯示用于創建或更新機會的表單

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 file app-routing.module.ts, and import the module by including it in the imports of main AppModule,

    添加單獨的模塊(其可被稱為AppRoutingModule )在一個文件中app-routing.module.ts ,并且通過包括它在導入模塊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插入與當前路徑匹配的組件的位置),

  • 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.tssrc/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 模塊構建

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/393034.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/393034.shtml
英文地址,請注明出處:http://en.pswp.cn/news/393034.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

leetcode74. 搜索二維矩陣(二分查找)

編寫一個高效的算法來判斷 m x n 矩陣中&#xff0c;是否存在一個目標值。該矩陣具有如下特性&#xff1a; 每行中的整數從左到右按升序排列。 每行的第一個整數大于前一行的最后一個整數。 示例 1: 輸入: matrix [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] tar…

搭建基于.NetFrameWork的私有nuget服務端及打包項目發布上傳

一、私有Nuget服務端搭建 1.創建一個.NetFramework web項目 2.在nuget管理中 安裝 nuget.server包 3.安裝完成后修改web.config里面的 apikey 和 packagesPath apikey&#xff1a;推送包到nuget服務端 packpage: 上傳上來的包存放的服務器位置 4.發布web項目到IIS中&#xff0c…

linux 網絡配置 阮一峰,Vim 配置入門

Vim 是最重要的編輯器之一&#xff0c;主要有下面幾個優點。可以不使用鼠標&#xff0c;完全用鍵盤操作。系統資源占用小&#xff0c;打開大文件毫無壓力。鍵盤命令變成肌肉記憶以后&#xff0c;操作速度極快。服務器默認都安裝 Vi 或 Vim。Vim 的配置不太容易&#xff0c;它有…

spring 之 property-placeholder 分析

不難知道&#xff0c; property-placeholder 的解析是 PropertyPlaceholderBeanDefinitionParser 完成的&#xff0c; 但是 它僅僅是個parser &#xff0c; 它僅僅是讀取了 location 等配置屬性&#xff0c; 并沒有完成真正的解析&#xff0c;及 注冊。 <context:property-p…

leetcode面試題 10.02. 變位詞組

編寫一種方法&#xff0c;對字符串數組進行排序&#xff0c;將所有變位詞組合在一起。變位詞是指字母相同&#xff0c;但排列不同的字符串。 注意&#xff1a;本題相對原題稍作修改 示例: 輸入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”], 輸出: [ [“ate”,…

hacktoberfest_我第一次參加Hacktoberfest中學到了什么

hacktoberfestImposter syndrome is something we all struggle with to one degree or another. Imposter syndrome is the fear of exposure as a fraud. If you’re anything like me you have felt like your work was not good enough to show. Or you weren’t far along…

--save 和--save-dev的區別

npm install 在安裝 npm 包時&#xff0c;有兩種命令參數可以把它們的信息寫入 package.json 文件&#xff0c;一個是npm install --save另一個是 npm install --save-dev&#xff0c;他們表面上的區別是--save 會把依賴包名稱添加到 package.json 文件 dependencies 鍵下&…

Linux 文件區塊連續嗎,關于Linux文件系統的的簡單理解和認識

關于Linux文件系統的的簡單理解和認識關于文件系統的運作&#xff0c;這與操作系統帶的檔案數據有關。例如Linux操作系統的檔案權限(rwx)與文件屬性(擁有者&#xff0c;群組&#xff0c;時間參數等)。文件系統通常會將這兩部分的數據分別存放在不同的區塊&#xff0c;權限與屬性…

服務器性能和活動監視

監視數據庫的目的是評估服務器的性能。 有效監視包括定期拍攝當前性能的快照來隔離導致問題的進程&#xff0c;以及連續收集數據來跟蹤性能趨勢。 Microsoft SQL Server 和 Microsoft 操作系統提供實用工具&#xff0c;使您可以查看數據庫的當前狀態并跟蹤性能的狀態變化。 下一…

Microsoft Desktop Virtualization

基本上有兩套啦&#xff0c;一是大家較為熟悉的MED-V。另外就是VDI(虛擬桌面基礎架構)&#xff0c;也就是以下的組合&#xff1a;1、Windows Server 2008 with Hyper-V 2、System Center Virtual Machine Manager (VMM) 2008 VMM 20083、Windows Vista Enterprise Centralized …

leetcode60. 第k個排列(回溯算法)

給出集合 [1,2,3,…,n]&#xff0c;其所有元素共有 n! 種排列。 按大小順序列出所有排列情況&#xff0c;并一一標記&#xff0c;當 n 3 時, 所有排列如下&#xff1a; “123” “132” “213” “231” “312” “321” 給定 n 和 k&#xff0c;返回第 k 個排列。 說明&…

webpack設置應用緩存_如何使用Webpack在Rails應用程序中設置TinyMCE

webpack設置應用緩存by Joanna Gaudyn喬安娜高登(Joanna Gaudyn) 如何使用Webpack在Rails應用程序中設置TinyMCE (How to setup TinyMCE in your Rails app using Webpack) The popularity of using Webpack to deal with your assets in Rails is steadily increasing. Getti…

springmvc ajax 頁面無法重定向問題!!!!

誒誒誒。這個問題困擾了我一天&#xff0c;百度了很多都不行。 剛實戰ssm框架&#xff0c;做登錄跳轉的時候&#xff0c;我是用ajax提交數據到后臺&#xff0c;然后后天返回數據進前臺&#xff0c;前臺再給用戶一些比較友好的提示&#xff0c;比如用戶名或密碼錯誤之類的。 所以…

linux svn log 亂碼,解決p42svn中文log亂碼的問題

現象&#xff1a;將perforce代碼庫遷移至SVN時log亂碼。p42svn.pl在windows下運行至"-|"時會報錯&#xff0c;于是安裝了linux虛擬機&#xff0c;從虛擬linux中運行p42svn.pl生成dump文件&#xff0c;再傳至windows下用svnadmin load。可是在svn查看log時&#xff0…

Django開發中常用的命令總結

1. 創建一個Django Project#使用下面的命令可以創建一個projectdjango-admin.py startproject mysite #創建好之后可以看到如下的pro... 1. 創建一個Django Project 1 2 3 4 5 6 7 8 9 10 11 #使用下面的命令可以創建一個project django-admin.py startproject mysite #創…

xml解析-jaxp添加結點

jaxp添加結點 eg&#xff1a; //在第一個下面添加nv / 1.創建解析器工廠 * 2.根據解析器工廠創建解析器 * 3.解析xml返回document * * 4.得到第一個p1 * -得到所有p1使用item方法得到第一個p1 * * 5.創建sex標簽 createElement * 6.創建文本 createTextNode * 7.把文本添加到se…

leetcode107. 二叉樹的層次遍歷 II

給定一個二叉樹&#xff0c;返回其節點值自底向上的層次遍歷。 &#xff08;即按從葉子節點所在層到根節點所在的層&#xff0c;逐層從左向右遍歷&#xff09;例如&#xff1a; 給定二叉樹 [3,9,20,null,null,15,7],3/ \9 20/ \15 7 返回其自底向上的層次遍歷為&#xff1a…

javascript 圖表_JavaScript 2018年的三個有爭議的圖表

javascript 圖表by Sacha Greif由Sacha Greif JavaScript 2018年的三個有爭議的圖表 (Three Controversial Charts From the State of JavaScript 2018) 您認為統計數據和圖表很無聊嗎&#xff1f; 再想一想… (You thought stats and graphs were boring? Think again…) “…

簽入在服務器上之后,別人獲取了,在解決方案資源管理器中找不到。

簽入在服務器上之后&#xff0c;別人獲取了&#xff0c;在解決方案資源管理器中找不到。 這個問題具體原因我也不太清楚&#xff0c;但是我找到了一個解決方案。直接在解決方案上右鍵&#xff0c;添加&#xff0c;添加現有項。把在解決方案資源管理器上看不見的選中&#xff0c…

03JavaScript程序設計修煉之道-2019-06-20_20-31-49

## DomDocument object model 文檔對象模型Dom樹html|head body| |meta title div|ul|li li li在js世界中&#xff0c;把dom樹的每個元素都看成一個對象&#xff0c;對象就有屬性和方法dom學什么 dom節點操作 查找元素 元素增刪改查 樣式操作 事件綁定等## 事件三要素 1 事件源…