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进行样式设置。 根据您的选择,您可以遵循单独的教程:

安装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 模块构建

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值