A 6-os szöglet kint van! Az új funkciók között szerepel a jobb teljesítmény, az új erőteljes CLI-kiegészítések és a szolgáltatások injektálásának új módja.
Ez az oktató kezdőknek szól. Az Angular példával tanulhatja meg egy teljes veremű CRUD - Létrehozás, Olvasás, Frissítés és Törlés - webalkalmazás felépítésével. A legnépszerűbb keretrendszer és platform legújabb verzióját fogjuk használni mobil és asztali kliensoldali alkalmazások felépítéséhez. Ezen alkalmazások neve SPA vagy Single Page Applications.
A háttérben használjuk a Python-ot a Djangóval. A Django a legnépszerűbb pythonikus webkeret, amelyet perfekcionisták számára terveztek, határidőkkel.
Dióhéjban megtanulják létrehozni az Angular 6 alkalmazásokat, létrehozni összetevőket és szolgáltatásokat, valamint hozzáadni az útválasztást. Azt is megtanulja, hogyan kell használni a különféle funkciókat, például a HttpClient az AJAX kérések és HTTP hívások küldésére, valamint az RxJS 6 megfigyelhetőségre való feliratkozásra és így tovább.
Ennek az Angular 6 oktatóanyagnak a végén megtanul egy valós példa alkalmazás elkészítésével:
- az Angular CLI legújabb verziójának telepítése,
- hogyan lehet használni az Angular 6 CLI-t egy új Angular 6 projekt létrehozásához,
- hogyan használjuk az Angular 6-ot egy egyszerű CRM alkalmazás felépítéséhez,
- mi a komponens és a komponens alapú architektúra
- hogyan kell használni az RxJS 6 megfigyelhető elemeket és operátorokat (
map()
ésfilter()
stb.) - hogyan lehet létrehozni az Angular 6 komponenseket,
- hogyan lehet hozzáadni az összetevők útvonalát és navigációját,
- hogyan lehet használni a HttpClient egy REST API stb.
A Django példa CRUD Back-End
Kihasználjuk a Django és a Django REST keretrendszerrel felépített egyszerű CRUD API-t. Mivel ez egy szögletes oktatóanyag, nem fogunk az API felépítésére koncentrálni. Ez egy külön oktatóanyag tárgya lesz. Megkaphatja a háttér-API forráskódját erről a lerakatról.
A következő parancsokat használhatja a fejlesztőkiszolgáló elindításához:
# Clone the project and navigate into it $ git clone //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
A szerver futni fog //localhost:8000
.
A pipenv-t, a Python hivatalosan ajánlott csomagkezelő eszközét használjuk. Telepítenie kell. A folyamat az operációs rendszertől függően meglehetősen egyszerű.
Szögletes 6 CRUD példa
A felépítendő Angular 6 alkalmazás példája a CRM RESTful API kezelőfelülete. Lehetővé teszi fiókok, leadek, lehetőségek és kapcsolattartók létrehozását. Tökéletes példa egy CRUD (Létrehozás, Olvasás, Frissítés és Törlés) alkalmazásra, amely SPA-ként (Single Page Application) épül fel.
A példaalkalmazás folyamatban van, ezért egy sor oktatóanyag segítségével építjük fel. Frissíteni fogják, hogy olyan speciális funkciókat tartalmazzon, mint az RxJS 6 és a JWT hitelesítés. A felhasználói felület összetevőinek felépítéséhez és stílusához a Bootstrap 4 és az Angular 6 anyagokat is felhasználjuk. A stílushoz vagy Bootstrap 4, vagy Angular Material kell. A választásától függően külön oktatóanyagokat követhet:
- Az UI építése Angular 6 anyaggal
- A felhasználói felület építése a Bootstrap 4 segítségével
A szögletes CLI telepítése (v6.0.0)
Győződjön meg róla, hogy a Node.js telepítve van, majd futtassa a következő parancsot a terminálon az Angular CLI v 6.0.0 telepítéséhez .
npm -g install @angular/cli
A telepített verziót a következő parancs futtatásával ellenőrizheti:
Most már készen áll egy projekt létrehozására az Angular CLI v6 használatával. Egyszerűen futtassa a következő parancsot a terminálon:
A CLI automatikusan létrehoz egy csomó fájlt, amelyek közösek a legtöbb Angular 6 projektben. Telepíti a projekt szükséges függőségeit is.
Leginkább a src/app
mappa belsejében fogunk dolgozni . Ez a projekt könyvtárszerkezete:

Az alábbi parancsok futtatásával lokálisan is kiszolgálhatja az alkalmazását:
# Navigate inside your project's folder $ cd crmapp # Serve your application $ ng serve
Az alkalmazás fut //localhost:4200
.
Ez az alkalmazás kezdőlapjának képernyőképe:

Komponensek szögben 6 | 5 | 4
Mi az alkatrész?
Az összetevő egy TypeScript osztály. HTML-sablonnal és opcionális CSS-stíluskészlettel rendelkezik, amelyek a képernyő egy részét irányítják.
A komponensek a legfontosabb fogalmak az Angular 6-ban. Az Angular 6 alkalmazás alapvetően egy gyökérösszetevővel rendelkező komponensek fája (a híres AppComponent ). A gyökérösszetevő a fő NgModule
modul bootstrap tömbjében található app.module.ts
.
Az alkatrészek egyik fontos szempontja az újrafelhasználhatóság. Egy alkatrész újból felhasználható az alkalmazás során, sőt más alkalmazásokban is. Egy bizonyos feladatot végrehajtó közös és megismételhető kód újrafelhasználható összetevőbe foglalható. Ez a komponens akkor hívható, amikor szükségünk van az általa nyújtott funkcionalitásra.
Minden bootstrapped komponens a saját komponensfájának alapja. A rendszerindító összetevő beillesztése általában az adott fát kitöltő összetevő-alkotások kaszkádját indítja el. ForrásKomponens alapú építészet
A szögletes alkalmazás több részből áll. Ezek az összetevők egy fa szerkezetet alkotnak a szülő és a gyermek alkotórészekkel.
Az alkatrész egy nagy rendszer (webalkalmazás) független blokkja. Bemenetek és kimenetek segítségével kommunikál a rendszer többi építőelemeivel (alkotóelemeivel). Egy összetevő társított nézettel, adatokkal és viselkedéssel rendelkezik. Lehet, hogy szülői és gyermeki összetevői vannak.
Az alkatrészek maximális újrafelhasználhatóságot, könnyű tesztelést, karbantartást és az aggályok elkülönítését teszik lehetővé.
Lássuk ezt most gyakorlatilag. Lépjen az Angular alkalmazás projekt mappájába, és nyissa meg a src/app
mappát. A következő fájlokat találja:
app.component.css
: the CSS file for the componentapp.component.html
: the HTML view for the componentapp.component.spec.ts
: the unit tests or spec file for the componentapp.component.ts
: the component code (data and behavior)app.module.ts
: the application main module
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.
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.
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:
- selector: specifies the tag that can be used to call this component in HTML templates just like the standard HTML tags
- 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)
- styleUrls: specifies an array of URLs for CSS style-sheets for the component
The export keyword is used to export the component so that it can be imported from other components and modules in the application.
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.
Now let’s see the corresponding template for this component. If you open src/app/app.component.html
this is what you'll find:
Welcome to !
![Angular Logo]()
Here are some links to help you start:
-
Tour of Heroes
CLI Documentation
Angular blog
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
; and ) 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.
You can also use other components directly inside Angular templates (via the selector property) just like normal 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.
Angular 6 Components by Example
After getting the theory behind Angular components, let’s now create the components for our simple CRM application.
Our REST API, built with Django, exposes these endpoints:
/api/accounts
: create or read a paginated list of accounts/api/accounts/<
id>: read, update or delete an account/api/contacts
: create or read a paginated list of contacts/api/contacts/<
id>: read, update or delete a contact/api/leads
: create or read a paginated list of leads/api/leads/<
id>: read, update or delete a lead/api/opportunities
: create or read a paginated list of opportunities/api/opportunities/<
id>: read, update or delete an opportunity
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:
AccountListComponent
: this component displays and controls a tabular list of accountsAccountCreateComponent
: this component displays and controls a form for creating or updating accountsContactListComponent
: displays a table of contactsContactCreateComponent
: displays a form to create or update a contactLeadListComponent
: displays a table of leadsLeadCreateComponent
: displays a form to create or update a leadOpportunityListComponent
: displays a table of opportunitiesOpportunityCreateComponent
: displays a form to create or update an opportunity
Let’s use the Angular CLI to create the components
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
.
If you open src/app/app.module.ts
after running all commands, you can see that all components are automatically added to the AppModuledeclarations
array.:
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.
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.
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
, - add
r-ou
tlet> in app.co
mponent.html (this is where the Angular Router will insert components matching the current path), 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
:
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:
{ path: '', redirectTo: 'accounts', pathMatch: 'full' },
The pathMatch specifies the matching strategy.
full
means that we want to fully match the path.
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:
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:
Accounts Create Account Contacts Create Contact Leads Create Lead Opportunities Create Opportunity
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.
First, you need to add the HttpClientModule module to the imports array of the main application module:
[..]import { HttpClientModule } from '@angular/common/http';@NgModule({declarations: [..],imports: [[..]HttpClientModule],providers: [],bootstrap: [AppComponent]})export class AppModule { }
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:
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.
Open
src/app/api.service.ts
then import and inject the HttpClient class.
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.
Getting Contacts/Sending HTTP GET Request Example
Let’s start with the contacts API endpoint.
First, we’ll add a method to consume this endpoint in our global API service,
next, we’ll inject the API service and call the method from the corresponding component class (
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:
export class APIService {API_URL = '//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:
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 = [];constructor(private apiService: APIService) { }ngOnInit() { this.getContacts();}public getContacts(){ this.apiService.getContacts().subscribe((data: Array) => { 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:
My Contacts
First Name
Last Name
Phone
Email
Address
{{ contact.first_name }}
{{ contact.last_name }}
{{ contact.phone }}
{{ contact.email }}
{{ contact.address }}
This is a screen-shot of the component:

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:
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:
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: "[email protected]", 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:
Create Contact
Create Contact
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.