- Angular 8 教程
- Angular 8 - 首页
- Angular 8 - 简介
- Angular 8 - 安装
- 创建第一个应用程序
- Angular 8 - 架构
- Angular 组件和模板
- Angular 8 - 数据绑定
- Angular 8 - 指令
- Angular 8 - 管道
- Angular 8 - 响应式编程
- 服务和依赖注入
- Angular 8 - Http 客户端编程
- Angular 8 - Angular Material
- 路由和导航
- Angular 8 - 动画
- Angular 8 - 表单
- Angular 8 - 表单验证
- 身份验证和授权
- Angular 8 - Web Workers
- Service Workers 和 PWA
- Angular 8 - 服务器端渲染
- Angular 8 - 国际化 (i18n)
- Angular 8 - 可访问性
- Angular 8 - CLI 命令
- Angular 8 - 测试
- Angular 8 - Ivy 编译器
- Angular 8 - 使用 Bazel 构建
- Angular 8 - 向后兼容性
- Angular 8 - 实用示例
- Angular 9 - 新特性?
- Angular 8 有用资源
- Angular 8 - 快速指南
- Angular 8 - 有用资源
- Angular 8 - 讨论
Angular 8 - 实用示例
在这里,我们将学习有关 Angular 8 的完整分步实用示例。
让我们创建一个 Angular 应用程序来检查我们日常的支出。让我们将我们的新应用程序命名为 ExpenseManager。
创建应用程序
使用以下命令创建新应用程序。
cd /path/to/workspace ng new expense-manager
这里:
new 是 ng CLI 应用程序的一个命令。它将用于创建新的应用程序。它会提出一些基本问题以便创建新的应用程序。让应用程序选择默认选项就足够了。关于如下提到的路由问题,请指定 否。
Would you like to add Angular routing? No
回答完基本问题后,ng CLI 应用程序会在 expense-manager 文件夹下创建一个新的 Angular 应用程序。
让我们进入我们新创建的应用程序文件夹。
cd expense-manager
让我们使用以下命令启动应用程序。
ng serve
让我们启动浏览器并打开 https://127.0.0.1:4200。浏览器将显示如下所示的应用程序:
让我们更改应用程序的标题以更好地反映我们的应用程序。打开 src/app/app.component.ts 并更改代码如下:
export class AppComponent { title = 'Expense Manager'; }
我们的最终应用程序将在浏览器中呈现,如下所示:
添加组件
使用 ng generate component 命令创建一个新组件,如下所示:
ng generate component expense-entry
输出
输出如下:
CREATE src/app/expense-entry/expense-entry.component.html (28 bytes) CREATE src/app/expense-entry/expense-entry.component.spec.ts (671 bytes) CREATE src/app/expense-entry/expense-entry.component.ts (296 bytes) CREATE src/app/expense-entry/expense-entry.component.css (0 bytes) UPDATE src/app/app.module.ts (431 bytes)
这里:
- ExpenseEntryComponent 创建在 src/app/expense-entry 文件夹下。
- 组件类、模板和样式表已创建。
- AppModule 已更新为包含新组件。
向 ExpenseEntryComponent (src/app/expense-entry/expense-entry.component.ts) 组件添加 title 属性。
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-expense-entry', templateUrl: './expense-entry.component.html', styleUrls: ['./expense-entry.component.css'] }) export class ExpenseEntryComponent implements OnInit { title: string; constructor() { } ngOnInit() { this.title = "Expense Entry" } }
使用以下内容更新模板 src/app/expense-entry/expense-entry.component.html。
<p>{{ title }}</p>
打开
src/app/app.component.html
并包含新创建的组件。<h1>{{ title }}</h1> <app-expense-entry></app-expense-entry>
这里:
app-expense-entry 是选择器值,可以用作常规 HTML 标签。
应用程序的输出如下所示:
包含 Bootstrap
让我们使用 styles 选项将 Bootstrap 包含到我们的 ExpenseManager 应用程序中,并将默认模板更改为使用 Bootstrap 组件。
打开命令提示符并转到 ExpenseManager 应用程序。
cd /go/to/expense-manager
使用以下命令安装 bootstrap 和 JQuery 库
npm install --save [email protected] [email protected]
这里:
我们安装了 JQuery,因为 Bootstrap 大量使用 jquery 来实现高级组件。
选项 angular.json 并设置 bootstrap 和 jquery 库路径。
{ "projects": { "expense-manager": { "architect": { "build": { "builder":"@angular-devkit/build-angular:browser", "options": { "outputPath": "dist/expense-manager", "index": "src/index.html", "main": "src/main.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.app.json", "aot": false, "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "./node_modules/bootstrap/dist/css/bootstrap.css", "src/styles.css" ], "scripts": [ "./node_modules/jquery/dist/jquery.js", "./node_modules/bootstrap/dist/js/bootstrap.js" ] }, }, } }}, "defaultProject": "expense-manager" }
这里:
scripts 选项用于包含 JavaScript 库。通过 scripts 注册的 JavaScript 将可用于应用程序中的所有 Angular 组件。
打开 app.component.html 并更改内容如下
<!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top"> <div class="container"> <a class="navbar-brand" href="#">{{ title }}</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"> </span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current) </span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#">Report</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Add Expense</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> </ul> </div> </div> </nav> <app-expense-entry></app-expense-entry>
这里:
使用了 Bootstrap 导航和容器。
打开 src/app/expense-entry/expense-entry.component.html 并放置以下内容。
<!-- Page Content --> <div class="container"> <div class="row"> <div class="col-lg-12 text-center" style="padding-top: 20px;"> <div class="container" style="padding-left: 0px; padding-right: 0px;"> <div class="row"> <div class="col-sm" style="text-align: left;"> {{ title }} </div> <div class="col-sm" style="text-align: right;"> <button type="button" class="btn btn-primary">Edit</button> </div> </div> </div> <div class="container box" style="margin-top: 10px;"> <div class="row"> <div class="col-2" style="text-align: right;"> <strong><em>Item:</em></strong> </div> <div class="col" style="text-align: left;"> Pizza </div> </div> <div class="row"> <div class="col-2" style="text-align: right;"> <strong><em>Amount:</em></strong> </div> <div class="col" style="text-align: left;"> 20 </div> </div> <div class="row"> <div class="col-2" style="text-align: right;"> <strong><em>Category:</em></strong> </div> <div class="col" style="text-align: left;"> Food </div> </div> <div class="row"> <div class="col-2" style="text-align: right;"> <strong><em>Location:</em></strong> </div> <div class="col" style="text-align: left;"> Zomato </div> </div> <div class="row"> <div class="col-2" style="text-align: right;"> <strong><em>Spend On:</em></strong> </div> <div class="col" style="text-align: left;"> June 20, 2020 </div> </div> </div> </div> </div> </div>
重新启动应用程序。
应用程序的输出如下所示:
我们将在下一章中改进应用程序以处理动态支出条目。
添加接口
创建 ExpenseEntry 接口 (src/app/expense-entry.ts) 并添加 id、amount、category、Location、spendOn 和 createdOn。
export interface ExpenseEntry { id: number; item: string; amount: number; category: string; location: string; spendOn: Date; createdOn: Date; }
将 ExpenseEntry 导入到 ExpenseEntryComponent 中。
import { ExpenseEntry } from '../expense-entry';
创建一个 ExpenseEntry 对象,expenseEntry 如下所示:
export class ExpenseEntryComponent implements OnInit { title: string; expenseEntry: ExpenseEntry; constructor() { } ngOnInit() { this.title = "Expense Entry"; this.expenseEntry = { id: 1, item: "Pizza", amount: 21, category: "Food", location: "Zomato", spendOn: new Date(2020, 6, 1, 10, 10, 10), createdOn: new Date(2020, 6, 1, 10, 10, 10), }; } }
使用 expenseEntry 对象,src/app/expense-entry/expense-entry.component.html 更新组件模板,如下所示:
<!-- Page Content --> <div class="container"> <div class="row"> <div class="col-lg-12 text-center" style="padding-top: 20px;"> <div class="container" style="padding-left: 0px; padding-right: 0px;"> <div class="row"> <div class="col-sm" style="text-align: left;"> {{ title }} </div> <div class="col-sm" style="text-align: right;"> <button type="button" class="btn btn-primary">Edit</button> </div> </div> </div> <div class="container box" style="margin-top: 10px;"> <div class="row"> <div class="col-2" style="text-align: right;"> <strong><em>Item:</em></strong> </div> <div class="col" style="text-align: left;"> {{ expenseEntry.item }} </div> </div> <div class="row"> <div class="col-2" style="text-align: right;"> <strong><em>Amount:</em></strong> </div> <div class="col" style="text-align: left;"> {{ expenseEntry.amount }} </div> </div> <div class="row"> <div class="col-2" style="text-align: right;"> <strong><em>Category:</em></strong> </div> <div class="col" style="text-align: left;"> {{ expenseEntry.category }} </div> </div> <div class="row"> <div class="col-2" style="text-align: right;"> <strong><em>Location:</em></strong> </div> <div class="col" style="text-align: left;"> {{ expenseEntry.location }} </div> </div> <div class="row"> <div class="col-2" style="text-align: right;"> <strong><em>Spend On:</em></strong> </div> <div class="col" style="text-align: left;"> {{ expenseEntry.spendOn }} </div> </div> </div> </div> </div> </div>
应用程序的输出如下所示:
使用指令
让我们在我们的 ExpenseManager 应用程序中添加一个新组件来列出支出条目。
打开命令提示符并转到项目根文件夹。
cd /go/to/expense-manager
启动应用程序。
ng serve
使用以下命令创建一个新组件,ExpenseEntryListComponent:
ng generate component ExpenseEntryList
输出
输出如下:
CREATE src/app/expense-entry-list/expense-entry-list.component.html (33 bytes) CREATE src/app/expense-entry-list/expense-entry-list.component.spec.ts (700 bytes) CREATE src/app/expense-entry-list/expense-entry-list.component.ts (315 bytes) CREATE src/app/expense-entry-list/expense-entry-list.component.css (0 bytes) UPDATE src/app/app.module.ts (548 bytes)
在这里,该命令创建了 ExpenseEntryList 组件并在 AppModule 中更新了必要的代码。
将 ExpenseEntry 导入到 ExpenseEntryListComponent 组件 (src/app/expense-entry-list/expense-entry-list.component)
import { ExpenseEntry } from '../expense-entry';
添加一个方法 getExpenseEntries() 来返回支出条目的列表(模拟项)在 ExpenseEntryListComponent (src/app/expense-entry-list/expense-entry-list.component)
getExpenseEntries() : ExpenseEntry[] { let mockExpenseEntries : ExpenseEntry[] = [ { id: 1, item: "Pizza", amount: Math.floor((Math.random() * 10) + 1), category: "Food", location: "Mcdonald", spendOn: new Date(2020, 4, Math.floor((Math.random() * 30) + 1), 10, 10, 10), createdOn: new Date(2020, 4, Math.floor((Math.random() * 30) + 1), 10, 10, 10) }, { id: 1, item: "Pizza", amount: Math.floor((Math.random() * 10) + 1), category: "Food", location: "KFC", spendOn: new Date(2020, 4, Math.floor((Math.random() * 30) + 1), 10, 10, 10), createdOn: new Date(2020, 4, Math.floor((Math.random() * 30) + 1), 10, 10, 10) }, { id: 1, item: "Pizza", amount: Math.floor((Math.random() * 10) + 1), category: "Food", location: "Mcdonald", spendOn: new Date(2020, 4, Math.floor((Math.random() * 30) + 1), 10, 10, 10), createdOn: new Date(2020, 4, Math.floor((Math.random() * 30) + 1), 10, 10, 10) }, { id: 1, item: "Pizza", amount: Math.floor((Math.random() * 10) + 1), category: "Food", location: "KFC", spendOn: new Date(2020, 4, Math.floor((Math.random() * 30) + 1), 10, 10, 10), createdOn: new Date(2020, 4, Math.floor((Math.random() * 30) + 1), 10, 10, 10) }, { id: 1, item: "Pizza", amount: Math.floor((Math.random() * 10) + 1), category: "Food", location: "KFC", spendOn: new Date(2020, 4, Math.floor((Math.random() * 30) + 1), 10, 10, 10), createdOn: new Date(2020, 4, Math.floor((Math.random() * 30) + 1), 10, 10, 10) }, ]; return mockExpenseEntries; }
声明一个局部变量 expenseEntries 并加载如下所示的模拟支出条目列表:
title: string; expenseEntries: ExpenseEntry[]; constructor() { } ngOnInit() { this.title = "Expense Entry List"; this.expenseEntries = this.getExpenseEntries(); }
打开模板文件 (src/app/expense-entry-list/expense-entry-list.component.html) 并在一个表中显示模拟条目。
<!-- Page Content --> <div class="container"> <div class="row"> <div class="col-lg-12 text-center" style="padding-top: 20px;"> <div class="container" style="padding-left: 0px; padding-right: 0px;"> <div class="row"> <div class="col-sm" style="text-align: left;"> {{ title }} </div> <div class="col-sm" style="text-align: right;"> <button type="button" class="btn btn-primary">Edit</button> </div> </div> </div> <div class="container box" style="margin-top: 10px;"> <table class="table table-striped"> <thead> <tr> <th>Item</th> <th>Amount</th> <th>Category</th> <th>Location</th> <th>Spent On</th> </tr> </thead> <tbody> <tr *ngFor="let entry of expenseEntries"> <th scope="row">{{ entry.item }}</th> <th>{{ entry.amount }}</th> <td>{{ entry.category }}</td> <td>{{ entry.location }}</td> <td>{{ entry.spendOn | date: 'short' }}</td> </tr> </tbody> </table> </div> </div> </div> </div>
这里:
使用了 Bootstrap 表格。table 和 table-striped 将根据 Bootstrap 样式标准设置表格样式。
使用 ngFor 遍历 expenseEntries 并生成表格行。
打开 AppComponent 模板 src/app/app.component.html 并包含 ExpenseEntryListComponent 并删除 ExpenseEntryComponent,如下所示:
... <app-expense-entry-list></app-expense-entry-list>
最后,应用程序的输出如下所示。
使用管道
让我们在我们的 ExpenseManager 应用程序中使用管道
打开 ExpenseEntryListComponent 的模板 src/app/expense-entry-list/expense-entry-list.component.html 并按照如下所示在 entry.spendOn 中包含管道:
<td>{{ entry.spendOn | date: 'short' }}</td>
在这里,我们使用了日期管道以简短格式显示支出日期。
最后,应用程序的输出如下所示:
添加调试服务
运行以下命令以生成 Angular 服务 DebugService。
ng g service debug
这将创建两个 TypeScript 文件(调试服务及其测试),如下所示:
CREATE src/app/debug.service.spec.ts (328 bytes) CREATE src/app/debug.service.ts (134 bytes)
让我们分析 DebugService 服务的内容。
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DebugService { constructor() { } }
这里:
@Injectable 装饰器附加到 DebugService 类,这使得 DebugService 可以在应用程序的 Angular 组件中使用。
providedIn 选项及其值 root 使 DebugService 可以在应用程序的所有组件中使用。
让我们添加一个方法 Info,它将消息打印到浏览器控制台。
info(message : String) : void { console.log(message); }
让我们在 ExpenseEntryListComponent 中初始化服务并使用它来打印消息。
import { Component, OnInit } from '@angular/core'; import { ExpenseEntry } from '../expense-entry'; import { DebugService } from '../debug.service'; @Component({ selector: 'app-expense-entry-list', templateUrl: './expense-entry-list.component.html', styleUrls: ['./expense-entry-list.component.css'] }) export class ExpenseEntryListComponent implements OnInit { title: string; expenseEntries: ExpenseEntry[]; constructor(private debugService: DebugService) { } ngOnInit() { this.debugService.info("Expense Entry List component initialized"); this.title = "Expense Entry List"; this.expenseEntries = this.getExpenseEntries(); } // other coding }
这里:
DebugService 使用构造函数参数初始化。设置类型为 DebugService 的参数 (debugService) 将触发依赖注入以创建一个新的 DebugService 对象并将其设置到 ExpenseEntryListComponent 组件中。
在 ngOnInit 方法中调用 DebugService 的 info 方法会在浏览器控制台中打印消息。
可以使用开发者工具查看结果,它看起来类似于以下所示:
让我们扩展应用程序以了解服务的范围。
让我们使用以下命令创建一个 DebugComponent。
ng generate component debug CREATE src/app/debug/debug.component.html (20 bytes) CREATE src/app/debug/debug.component.spec.ts (621 bytes) CREATE src/app/debug/debug.component.ts (265 bytes) CREATE src/app/debug/debug.component.css (0 bytes) UPDATE src/app/app.module.ts (392 bytes)
让我们删除根模块中的 DebugService。
// src/app/debug.service.ts import { Injectable } from '@angular/core'; @Injectable() export class DebugService { constructor() { } info(message : String) : void { console.log(message); } }
在 ExpenseEntryListComponent 组件下注册 DebugService。
// src/app/expense-entry-list/expense-entry-list.component.ts @Component({ selector: 'app-expense-entry-list', templateUrl: './expense-entry-list.component.html', styleUrls: ['./expense-entry-list.component.css'] providers: [DebugService] })
在这里,我们使用了 providers 元数据 (ElementInjector) 来注册服务。
打开 DebugComponent (src/app/debug/debug.component.ts) 并导入 DebugService,并在组件的构造函数中设置一个实例。
import { Component, OnInit } from '@angular/core'; import { DebugService } from '../debug.service'; @Component({ selector: 'app-debug', templateUrl: './debug.component.html', styleUrls: ['./debug.component.css'] }) export class DebugComponent implements OnInit { constructor(private debugService: DebugService) { } ngOnInit() { this.debugService.info("Debug component gets service from Parent"); } }
在这里,我们没有注册 DebugService。因此,如果用作父组件,则 DebugService 将不可用。如果父组件可以使用该服务,则在父组件内使用时,该服务可能可从父组件获取。
打开 ExpenseEntryListComponent 模板 (src/app/expense-entry-list/expense-entry-list.component.html) 并包含如下所示的内容部分
// existing content <app-debug></app-debug> <ng-content></ng-content>
在这里,我们包含了一个内容部分和 DebugComponent 部分。
让我们在 AppComponent 模板中将 debug 组件作为内容包含在 ExpenseEntryListComponent 组件中。打开 AppComponent 模板并将 app-expense-entry-list 更改如下:
// navigation code <app-expense-entry-list> <app-debug></app-debug> </app-expense-entry-list>
在这里,我们包含了 DebugComponent 作为内容。
让我们检查应用程序,它将在页面末尾显示 DebugService 模板,如下所示:
此外,我们还可以在控制台中看到来自 debug 组件的两个调试信息。这表明 debug 组件从其父组件获取服务。
让我们更改在 ExpenseEntryListComponent 中注入服务的方式以及它如何影响服务的范围。将 providers 注入器更改为 viewProviders 注入。viewProviders 不会将服务注入到内容子元素中,因此它应该会失败。
viewProviders: [DebugService]
检查应用程序,您将看到一个 debug 组件(用作内容子元素)会抛出错误,如下所示:
让我们删除模板中的 debug 组件并恢复应用程序。
打开 ExpenseEntryListComponent 模板 (src/app/expense-entry-list/expense-entry-list.component.html) 并删除以下内容
<app-debug></app-debug> <ng-content></ng-content>
打开 AppComponent 模板并将 app-expense-entry-list 更改如下:
// navigation code <app-expense-entry-list> </app-expense-entry-list>
将 ExpenseEntryListComponent 中的 viewProviders 设置更改为 providers。
providers: [DebugService]
重新运行应用程序并检查结果。
创建支出服务
让我们在我们的 ExpenseManager 应用程序中创建一个新的服务 ExpenseEntryService 来与 Expense REST API 进行交互。ExpenseEntryService 将获取最新的支出条目、插入新的支出条目、修改现有的支出条目并删除不需要的支出条目。
打开命令提示符并转到项目根文件夹。
cd /go/to/expense-manager
启动应用程序。
ng serve
运行以下命令以生成 Angular 服务 ExpenseService。
ng generate service ExpenseEntry
这将创建两个 TypeScript 文件(支出条目服务及其测试),如下所示:
CREATE src/app/expense-entry.service.spec.ts (364 bytes) CREATE src/app/expense-entry.service.ts (141 bytes)
打开 ExpenseEntryService (src/app/expense-entry.service.ts) 并从 rxjs 库导入 ExpenseEntry、throwError 和 catchError,并从 @angular/common/http 包导入 HttpClient、HttpHeaders 和 HttpErrorResponse。
import { Injectable } from '@angular/core'; import { ExpenseEntry } from './expense-entry'; import { throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
将 HttpClient 服务注入到我们的服务中。
constructor(private httpClient : HttpClient) { }
创建一个变量 expenseRestUrl 来指定 Expense Rest API 端点。
private expenseRestUrl = 'https://127.0.0.1:8000/api/expense';
创建一个变量 httpOptions 来设置 Http Header 选项。这将在 Angular HttpClient 服务调用 Http Rest API 时使用。
private httpOptions = { headers: new HttpHeaders( { 'Content-Type': 'application/json' }) };
完整代码如下:
import { Injectable } from '@angular/core'; import { ExpenseEntry } from './expense-entry'; import { Observable, throwError } from 'rxjs'; import { catchError, retry } from 'rxjs/operators'; import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class ExpenseEntryService { private expenseRestUrl = 'api/expense'; private httpOptions = { headers: new HttpHeaders( { 'Content-Type': 'application/json' }) }; constructor( private httpClient : HttpClient) { } }
使用 HttpClient 服务进行 Http 编程
启动 Expense REST API 应用程序,如下所示:
cd /go/to/expense-rest-api node .\server.js
在 ExpenseEntryService (src/app/expense-entry.service.ts) 服务中添加 getExpenseEntries() 和 httpErrorHandler() 方法。
getExpenseEntries() : Observable<ExpenseEntry[]> { return this.httpClient.get<ExpenseEntry[]>(this.expenseRestUrl, this.httpOptions) .pipe(retry(3),catchError(this.httpErrorHandler)); } getExpenseEntry(id: number) : Observable<ExpenseEntry> { return this.httpClient.get<ExpenseEntry>(this.expenseRestUrl + "/" + id, this.httpOptions) .pipe( retry(3), catchError(this.httpErrorHandler) ); } private httpErrorHandler (error: HttpErrorResponse) { if (error.error instanceof ErrorEvent) { console.error("A client side error occurs. The error message is " + error.message); } else { console.error( "An error happened in server. The HTTP status code is " + error.status + " and the error returned is " + error.message); } return throwError("Error occurred. Pleas try again"); }
这里:
getExpenseEntries() 使用支出端点调用 get() 方法,并配置错误处理程序。此外,它还配置 httpClient 以在失败的情况下最多尝试 3 次。最后,它将服务器响应作为类型化 (ExpenseEntry[]) Observable 对象返回。
getExpenseEntry 与 getExpenseEntries() 类似,只是它传递 ExpenseEntry 对象的 id 并获取 ExpenseEntry Observable 对象。
ExpenseEntryService 的完整代码如下:
import { Injectable } from '@angular/core'; import { ExpenseEntry } from './expense-entry'; import { Observable, throwError } from 'rxjs'; import { catchError, retry } from 'rxjs/operators'; import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class ExpenseEntryService { private expenseRestUrl = 'https://127.0.0.1:8000/api/expense'; private httpOptions = { headers: new HttpHeaders( { 'Content-Type': 'application/json' }) }; constructor(private httpClient : HttpClient) { } getExpenseEntries() : Observable{ return this.httpClient.get (this.expenseRestUrl, this.httpOptions) .pipe( retry(3), catchError(this.httpErrorHandler) ); } getExpenseEntry(id: number) : Observable { return this.httpClient.get (this.expenseRestUrl + "/" + id, this.httpOptions) .pipe( retry(3), catchError(this.httpErrorHandler) ); } private httpErrorHandler (error: HttpErrorResponse) { if (error.error instanceof ErrorEvent) { console.error("A client side error occurs. The error message is " + error.message); } else { console.error( "An error happened in server. The HTTP status code is " + error.status + " and the error returned is " + error.message); } return throwError("Error occurred. Pleas try again"); } }
打开 ExpenseEntryListComponent (src-entry-list-entry-list.component.ts) 并通过构造函数注入 ExpenseEntryService,如下所示
constructor(private debugService: DebugService, private restService : ExpenseEntryService ) { }
更改 getExpenseEntries() 函数。调用 ExpenseEntryService 中的 getExpenseEntries() 方法,而不是返回模拟项。
getExpenseItems() { this.restService.getExpenseEntries() .subscribe( data =− this.expenseEntries = data ); }
ExpenseEntryListComponent 的完整代码如下:
import { Component, OnInit } from '@angular/core'; import { ExpenseEntry } from '../expense-entry'; import { DebugService } from '../debug.service'; import { ExpenseEntryService } from '../expense-entry.service'; @Component({ selector: 'app-expense-entry-list', templateUrl: './expense-entry-list.component.html', styleUrls: ['./expense-entry-list.component.css'], providers: [DebugService] }) export class ExpenseEntryListComponent implements OnInit { title: string; expenseEntries: ExpenseEntry[]; constructor(private debugService: DebugService, private restService : ExpenseEntryService ) { } ngOnInit() { this.debugService.info("Expense Entry List component initialized"); this.title = "Expense Entry List"; this.getExpenseItems(); } getExpenseItems() { this.restService.getExpenseEntries() .subscribe( data => this.expenseEntries = data ); } }
最后,检查应用程序,您将看到以下响应。
添加支出功能
让我们在我们的 ExpenseEntryService 中添加一个新方法 addExpenseEntry() 来添加新的支出条目,如下所示:
addExpenseEntry(expenseEntry: ExpenseEntry): Observable<ExpenseEntry> { return this.httpClient.post<ExpenseEntry>(this.expenseRestUrl, expenseEntry, this.httpOptions) .pipe( retry(3), catchError(this.httpErrorHandler) ); }
更新支出条目功能
让我们在ExpenseEntryService中添加一个新的方法updateExpenseEntry(),用于更新现有的支出条目,如下所示
updateExpenseEntry(expenseEntry: ExpenseEntry): Observable<ExpenseEntry> { return this.httpClient.put<ExpenseEntry>(this.expenseRestUrl + "/" + expenseEntry.id, expenseEntry, this.httpOptions) .pipe( retry(3), catchError(this.httpErrorHandler) ); }
删除支出条目功能
让我们在ExpenseEntryService中添加一个新的方法deleteExpenseEntry(),用于删除现有的支出条目,如下所示:
deleteExpenseEntry(expenseEntry: ExpenseEntry | number) : Observable<ExpenseEntry> { const id = typeof expenseEntry == 'number' ? expenseEntry : expenseEntry.id const url = `${this.expenseRestUrl}/${id}`; return this.httpClient.delete<ExpenseEntry>(url, this.httpOptions) .pipe( retry(3), catchError(this.httpErrorHandler) ); }
添加路由
如果之前没有完成,请使用以下命令生成路由模块。
ng generate module app-routing --module app --flat
输出
输出如下所示:
CREATE src/app/app-routing.module.ts (196 bytes) UPDATE src/app/app.module.ts (785 bytes)
这里:
CLI生成AppRoutingModule,然后在AppModule中配置它。
更新AppRoutingModule (src/app/app.module.ts),如下所示:
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { ExpenseEntryComponent } from './expense-entry/expense-entry.component'; import { ExpenseEntryListComponent } from './expense-entry-list/expense-entry-list.component'; const routes: Routes = [ { path: 'expenses', component: ExpenseEntryListComponent }, { path: 'expenses/detail/:id', component: ExpenseEntryComponent }, { path: '', redirectTo: 'expenses', pathMatch: 'full' }]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
在这里,我们为支出列表和支出详情组件添加了路由。
更新AppComponent模板(src/app/app.component.html)以包含router-outlet和routerLink。
<!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top"> <div class="container"> <a class="navbar-brand" href="#">{{ title }}</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only" routerLink="/">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" routerLink="/expenses">Report</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Add Expense</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> </ul> </div> </div> </nav> <router-outlet></router-outlet>
打开ExpenseEntryListComponent模板(src/app/expense-entry-list/expense-entry-list.component.html)并为每个支出条目包含查看选项。
<table class="table table-striped"> <thead> <tr> <th>Item</th> <th>Amount</th> <th>Category</th> <th>Location</th> <th>Spent On</th> <th>View</th> </tr> </thead> <tbody> <tr *ngFor="let entry of expenseEntries"> <th scope="row">{{ entry.item }}</th> <th>{{ entry.amount }}</th> <td>{{ entry.category }}</td> <td>{{ entry.location }}</td> <td>{{ entry.spendOn | date: 'medium' }}</td> <td><a routerLink="../expenses/detail/{{ entry.id }}">View</a></td> </tr> </tbody> </table>
在这里,我们更新了支出列表表格,并添加了一列来显示查看选项。
打开ExpenseEntryComponent (src/app/expense-entry/expense-entry.component.ts)并添加功能以获取当前选定的支出条目。这可以通过首先通过paramMap获取ID,然后使用ExpenseEntryService中的getExpenseEntry()方法来完成。
this.expenseEntry$ = this.route.paramMap.pipe( switchMap(params => { this.selectedId = Number(params.get('id')); return this.restService.getExpenseEntry(this.selectedId); })); this.expenseEntry$.subscribe( (data) => this.expenseEntry = data );
更新ExpenseEntryComponent并添加转到支出列表的选项。
goToList() { this.router.navigate(['/expenses']); }
ExpenseEntryComponent的完整代码如下:
import { Component, OnInit } from '@angular/core'; import { ExpenseEntry } from '../expense-entry'; import { ExpenseEntryService } from '../expense-entry.service'; import { Router, ActivatedRoute } from '@angular/router'; import { Observable } from 'rxjs'; import { switchMap } from 'rxjs/operators'; @Component({ selector: 'app-expense-entry', templateUrl: './expense-entry.component.html', styleUrls: ['./expense-entry.component.css'] }) export class ExpenseEntryComponent implements OnInit { title: string; expenseEntry$ : Observable<ExpenseEntry>; expenseEntry: ExpenseEntry = {} as ExpenseEntry; selectedId: number; constructor(private restService : ExpenseEntryService, private router : Router, private route : ActivatedRoute ) { } ngOnInit() { this.title = "Expense Entry"; this.expenseEntry$ = this.route.paramMap.pipe( switchMap(params => { this.selectedId = Number(params.get('id')); return this.restService.getExpenseEntry(this.selectedId); })); this.expenseEntry$.subscribe( (data) => this.expenseEntry = data ); } goToList() { this.router.navigate(['/expenses']); } }
打开ExpenseEntryComponent (src/app/expense-entry/expense-entry.component.html)模板并添加一个新按钮以导航回支出列表页面。
<div class="col-sm" style="text-align: right;"> <button type="button" class="btn btn-primary" (click)="goToList()">Go to List</button> <button type="button" class="btn btn-primary">Edit</button> </div>
在这里,我们在编辑按钮之前添加了转到列表按钮。
使用以下命令运行应用程序:
ng serve
应用程序的最终输出如下所示:
单击第一个条目的查看选项将导航到详细信息页面并显示所选的支出条目,如下所示:
启用登录和注销功能
创建一个新的服务AuthService来验证用户。
ng generate service auth CREATE src/app/auth.service.spec.ts (323 bytes) CREATE src/app/auth.service.ts (133 bytes)
打开AuthService并包含以下代码。
import { Injectable } from '@angular/core'; import { Observable, of } from 'rxjs'; import { tap, delay } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class AuthService { isUserLoggedIn: boolean = false; login(userName: string, password: string): Observable{ console.log(userName); console.log(password); this.isUserLoggedIn = userName == 'admin' && password == 'admin'; localStorage.setItem('isUserLoggedIn', this.isUserLoggedIn ? "true" : "false"); return of(this.isUserLoggedIn).pipe( delay(1000), tap(val => { console.log("Is User Authentication is successful: " + val); }) ); } logout(): void { this.isUserLoggedIn = false; localStorage.removeItem('isUserLoggedIn'); } constructor() { } }
这里:
我们编写了两个方法,login和logout。
login方法的目的是验证用户,如果用户成功验证,则将信息存储在localStorage中,然后返回true。
身份验证验证是用户名和密码应为admin。
我们没有使用任何后端。相反,我们使用Observables模拟了1秒的延迟。
logout方法的目的是使用户无效并删除存储在localStorage中的信息。
使用以下命令创建一个login组件:
ng generate component login CREATE src/app/login/login.component.html (20 bytes) CREATE src/app/login/login.component.spec.ts (621 bytes) CREATE src/app/login/login.component.ts (265 bytes) CREATE src/app/login/login.component.css (0 bytes) UPDATE src/app/app.module.ts (1207 bytes)
打开LoginComponent并包含以下代码:
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; import { AuthService } from '../auth.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { userName: string; password: string; formData: FormGroup; constructor(private authService : AuthService, private router : Router) { } ngOnInit() { this.formData = new FormGroup({ userName: new FormControl("admin"), password: new FormControl("admin"), }); } onClickSubmit(data: any) { this.userName = data.userName; this.password = data.password; console.log("Login page: " + this.userName); console.log("Login page: " + this.password); this.authService.login(this.userName, this.password) .subscribe( data => { console.log("Is Login Success: " + data); if(data) this.router.navigate(['/expenses']); }); } }
这里:
使用了响应式表单。
导入了AuthService和Router并在构造函数中对其进行了配置。
创建了FormGroup的一个实例,并包含了FormControl的两个实例,一个用于用户名,另一个用于密码。
创建了一个onClickSubmit来使用authService验证用户,如果成功,则导航到支出列表。
打开LoginComponent模板并包含以下模板代码。
<!-- Page Content --> <div class="container"> <div class="row"> <div class="col-lg-12 text-center" style="padding-top: 20px;"> <div class="container box" style="margin-top: 10px; padding-left: 0px; padding-right: 0px;"> <div class="row"> <div class="col-12" style="text-align: center;"> <form [formGroup]="formData" (ngSubmit)="onClickSubmit(formData.value)" class="form-signin"> <h2 class="form-signin-heading">Please sign in</h2> <label for="inputEmail" class="sr-only">Email address</label> <input type="text" id="username" class="form-control" formControlName="userName" placeholder="Username" required autofocus> <label for="inputPassword" class="sr-only">Password</label> <input type="password" id="inputPassword" class="form-control" formControlName="password" placeholder="Password" required> <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> </form> </div> </div> </div> </div> </div> </div>
这里:
创建了一个响应式表单并设计了一个登录表单。
将onClickSubmit方法附加到表单提交操作。
打开LoginComponent样式并包含以下CSS代码。
.form-signin { max-width: 330px; padding: 15px; margin: 0 auto; } input { margin-bottom: 20px; }
在这里,添加了一些样式来设计登录表单。
使用以下命令创建一个注销组件:
ng generate component logout CREATE src/app/logout/logout.component.html (21 bytes) CREATE src/app/logout/logout.component.spec.ts (628 bytes) CREATE src/app/logout/logout.component.ts (269 bytes) CREATE src/app/logout/logout.component.css (0 bytes) UPDATE src/app/app.module.ts (1368 bytes)
打开LogoutComponent并包含以下代码。
import { Component, OnInit } from '@angular/core'; import { AuthService } from '../auth.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-logout', templateUrl: './logout.component.html', styleUrls: ['./logout.component.css'] }) export class LogoutComponent implements OnInit { constructor(private authService : AuthService, private router: Router) { } ngOnInit() { this.authService.logout(); this.router.navigate(['/']); } }
这里:
- 使用了AuthService的注销方法。
- 注销用户后,页面将重定向到主页(/)。
使用以下命令创建一个守卫:
ng generate guard expense CREATE src/app/expense.guard.spec.ts (364 bytes) CREATE src/app/expense.guard.ts (459 bytes)
打开ExpenseGuard并包含以下代码:
import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, UrlTree } from '@angular/router'; import { Observable } from 'rxjs'; import { AuthService } from './auth.service'; @Injectable({ providedIn: 'root' }) export class ExpenseGuard implements CanActivate { constructor(private authService: AuthService, private router: Router) {} canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree { let url: string = state.url; return this.checkLogin(url); } checkLogin(url: string): true | UrlTree { console.log("Url: " + url) let val: string = localStorage.getItem('isUserLoggedIn'); if(val != null && val == "true"){ if(url == "/login") this.router.parseUrl('/expenses'); else return true; } else { return this.router.parseUrl('/login'); } } }
这里:
- checkLogin将检查localStorage是否包含用户信息,如果可用,则返回true。
- 如果用户已登录并转到登录页面,它将把用户重定向到支出页面。
- 如果用户未登录,则用户将被重定向到登录页面。
打开AppRoutingModule (src/app/app-routing.module.ts)并更新以下代码:
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { ExpenseEntryComponent } from './expense-entry/expense-entry.component'; import { ExpenseEntryListComponent } from './expense-entry-list/expense-entry-list.component'; import { LoginComponent } from './login/login.component'; import { LogoutComponent } from './logout/logout.component'; import { ExpenseGuard } from './expense.guard'; const routes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'logout', component: LogoutComponent }, { path: 'expenses', component: ExpenseEntryListComponent, canActivate: [ExpenseGuard]}, { path: 'expenses/detail/:id', component: ExpenseEntryComponent, canActivate: [ExpenseGuard]}, { path: '', redirectTo: 'expenses', pathMatch: 'full' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
这里:
- 导入了LoginComponent和LogoutComponent。
- 导入了ExpenseGuard。
- 创建了两个新路由,login和logout,分别用于访问LoginComponent和LogoutComponent。
- 为ExpenseEntryComponent和ExpenseEntryListComponent添加新的选项canActivate。
打开AppComponent模板并添加两个登录和注销链接。
<div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only" routerLink="/">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" routerLink="/expenses">Report</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Add Expense</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> <li class="nav-item"> <div *ngIf="isUserLoggedIn; else isLogOut"> <a class="nav-link" routerLink="/logout">Logout</a> </div> <ng-template #isLogOut> <a class="nav-link" routerLink="/login">Login</a> </ng-template> </li> </ul> </div>
打开AppComponent并更新以下代码:
import { Component } from '@angular/core'; import { AuthService } from './auth.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Expense Manager'; isUserLoggedIn = false; constructor(private authService: AuthService) {} ngOnInit() { let storeData = localStorage.getItem("isUserLoggedIn"); console.log("StoreData: " + storeData); if( storeData != null && storeData == "true") this.isUserLoggedIn = true; else this.isUserLoggedIn = false; } }
在这里,我们添加了识别用户状态的逻辑,以便我们可以显示登录/注销功能。
打开AppModule (src/app/app.module.ts)并配置ReactiveFormsModule
import { ReactiveFormsModule } from '@angular/forms'; imports: [ ReactiveFormsModule ]
现在,运行应用程序,应用程序将打开登录页面。
输入admin和admin作为用户名和密码,然后单击提交。应用程序处理登录并将用户重定向到支出列表页面,如下所示:
最后,您可以单击注销并退出应用程序。
添加/编辑/删除支出
添加一个新组件EditEntryComponent,使用以下命令添加新的支出条目并编辑现有的支出条目:
ng generate component EditEntry CREATE src/app/edit-entry/edit-entry.component.html (25 bytes) CREATE src/app/edit-entry/edit-entry.component.spec.ts (650 bytes) CREATE src/app/edit-entry/edit-entry.component.ts (284 bytes) CREATE src/app/edit-entry/edit-entry.component.css (0 bytes) UPDATE src/app/app.module.ts (1146 bytes)
使用以下代码更新EditEntryComponent:
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { ExpenseEntry } from '../expense-entry'; import { ExpenseEntryService } from '../expense-entry.service'; import { Router, ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-edit-entry', templateUrl: './edit-entry.component.html', styleUrls: ['./edit-entry.component.css'] }) export class EditEntryComponent implements OnInit { id: number; item: string; amount: number; category: string; location: string; spendOn: Date; formData: FormGroup; selectedId: number; expenseEntry: ExpenseEntry; constructor(private expenseEntryService : ExpenseEntryService, private router: Router, private route: ActivatedRoute) { } ngOnInit() { this.formData = new FormGroup({ id: new FormControl(), item: new FormControl('', [Validators.required]), amount: new FormControl('', [Validators.required]), category: new FormControl(), location: new FormControl(), spendOn: new FormControl() }); this.selectedId = Number(this.route.snapshot.paramMap.get('id')); if(this.selectedId != null && this.selectedId != 0) { this.expenseEntryService.getExpenseEntry(this.selectedId) .subscribe( (data) => { this.expenseEntry = data; this.formData.controls['id'].setValue(this.expenseEntry.id); this.formData.controls['item'].setValue(this.expenseEntry.item); this.formData.controls['amount'].setValue(this.expenseEntry.amount); this.formData.controls['category'].setValue(this.expenseEntry.category); this.formData.controls['location'].setValue(this.expenseEntry.location); this.formData.controls['spendOn'].setValue(this.expenseEntry.spendOn); }) } } get itemValue() { return this.formData.get('item'); } get amountValue() { return this.formData.get('amount'); } onClickSubmit(data: any) { console.log('onClickSubmit fired'); this.id = data.id; this.item = data.item; this.amount = data.amount; this.category = data.category; this.location = data.location; this.spendOn = data.spendOn; let expenseEntry : ExpenseEntry = { id: this.id, item: this.item, amount: this.amount, category: this.category, location: this.location, spendOn: this.spendOn, createdOn: new Date(2020, 5, 20) } console.log(expenseEntry); if(expenseEntry.id == null || expenseEntry.id == 0) { console.log('add fn fired'); this.expenseEntryService.addExpenseEntry(expenseEntry) .subscribe( data => { console.log(data); this.router.navigate(['/expenses']); }); } else { console.log('edit fn fired'); this.expenseEntryService.updateExpenseEntry(expenseEntry) .subscribe( data => { console.log(data); this.router.navigate(['/expenses']); }); } } }
这里:
在ngOnInit方法中使用FormControl和FormGroup类以及适当的验证规则创建了一个表单formData。
在ngOnInit方法中加载要编辑的支出条目。
创建了两个方法itemValue和amountValue,分别用于获取用户为验证目的输入的项目和金额值。
创建了方法onClickSubmit来保存(添加/更新)支出条目。
使用支出服务添加和更新支出条目。
使用支出表单更新EditEntryComponent模板,如下所示:
<!-- Page Content --> <div class="container"> <div class="row"> <div class="col-lg-12 text-center" style="padding-top: 20px;"> <div class="container" style="padding-left: 0px; padding-right: 0px;"> </div> <div class="container box" style="margin-top: 10px;"> <form [formGroup]="formData" (ngSubmit)="onClickSubmit(formData.value)" class="form" novalidate> <div class="form-group"> <label for="item">Item</label> <input type="hidden" class="form-control" id="id" formControlName="id"> <input type="text" class="form-control" id="item" formControlName="item"> <div *ngIf="!itemValue?.valid && (itemValue?.dirty ||itemValue?.touched)"> <div [hidden]="!itemValue.errors.required"> Item is required </div> </div> </div> <div class="form-group"> <label for="amount">Amount</label> <input type="text" class="form-control" id="amount" formControlName="amount"> <div *ngIf="!amountValue?.valid && (amountValue?.dirty ||amountValue?.touched)"> <div [hidden]="!amountValue.errors.required"> Amount is required </div> </div> </div> <div class="form-group"> <label for="category">Category</label> <select class="form-control" id="category" formControlName="category"> <option>Food</option> <option>Vegetables</option> <option>Fruit</option> <option>Electronic Item</option> <option>Bill</option> </select> </div> <div class="form-group"> <label for="location">location</label> <input type="text" class="form-control" id="location" formControlName="location"> </div> <div class="form-group"> <label for="spendOn">spendOn</label> <input type="text" class="form-control" id="spendOn" formControlName="spendOn"> </div> <button class="btn btn-lg btn-primary btn-block" type="submit" [disabled]="!formData.valid">Submit</button> </form> </div> </div> </div> </div>
这里:
创建了一个表单并将其绑定到在类中创建的表单formData。
将item和amount验证为必需值。
验证成功后调用onClickSubmit函数。
打开EditEntryComponent样式表并更新以下代码:
.form { max-width: 330px; padding: 15px; margin: 0 auto; } .form label { text-align: left; width: 100%; } input { margin-bottom: 20px; }
在这里,我们设计了支出条目表单的样式。
使用以下命令添加AboutComponent
ng generate component About CREATE src/app/about/about.component.html (20 bytes) CREATE src/app/about/about.component.spec.ts (621 bytes) CREATE src/app/about/about.component.ts (265 bytes) CREATE src/app/about/about.component.css (0 bytes) UPDATE src/app/app.module.ts (1120 bytes)
打开AboutComponent并添加如下所示的标题:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-about', templateUrl: './about.component.html', styleUrls: ['./about.component.css'] }) export class AboutComponent implements OnInit { title = "About"; constructor() { } ngOnInit() { } }
打开AboutComponent模板并更新如下所示的内容:
<!-- Page Content --> <div class="container"> <div class="row"> <div class="col-lg-12 text-center" style="padding-top: 20px;"> <div class="container" style="padding-left: 0px; padding-right: 0px;"> <div class="row"> <div class="col-sm" style="text-align: left;"> <h1>{{ title }}</h1> </div> </div> </div> <div class="container box" style="margin-top: 10px;"> <div class="row"> <div class="col" style="text-align: left;"> <p>Expense management Application</p> </div> </div> </div> </div> </div> </div>
添加添加和编辑支出条目的路由,如下所示
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { ExpenseEntryComponent } from './expense-entry/expense-entry.component'; import { ExpenseEntryListComponent } from './expense-entry-list/expense-entry-list.component'; import { LoginComponent } from './login/login.component'; import { LogoutComponent } from './logout/logout.component'; import { EditEntryComponent } from './edit-entry/edit-entry.component'; import { AboutComponent } from './about/about.component'; import { ExpenseGuard } from './expense.guard'; const routes: Routes = [ { path: 'about', component: AboutComponent }, { path: 'login', component: LoginComponent }, { path: 'logout', component: LogoutComponent }, { path: 'expenses', component: ExpenseEntryListComponent, canActivate: [ExpenseGuard]}, { path: 'expenses/detail/:id', component: ExpenseEntryComponent, canActivate: [ExpenseGuard]}, { path: 'expenses/add', component: EditEntryComponent, canActivate: [ExpenseGuard]}, { path: 'expenses/edit/:id', component: EditEntryComponent, canActivate: [ExpenseGuard]}, { path: '', redirectTo: 'expenses', pathMatch: 'full' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
在这里,我们添加了关于、添加支出和编辑支出路由。
在ExpenseEntryListComponent模板中添加编辑和删除链接。
<table class="table table-striped"> <thead> <tr> <th>Item</th> <th>Amount</th> <th>Category</th> <th>Location</th> <th>Spent On</th> <th>View</th> <th>Edit</th> <th>Delete</th> </tr> </thead> <tbody> <tr *ngFor="let entry of expenseEntries"> <th scope="row">{{ entry.item }}</th> <th>{{ entry.amount }}</th> <td>{{ entry.category }}</td> <td>{{ entry.location }}</td> <td>{{ entry.spendOn | date: 'medium' }}</td> <td><a routerLink="../expenses/detail/{{ entry.id }}">View</a></td> <td><a routerLink="../expenses/edit/{{ entry.id }}">Edit</a></td> <td><a href="#" (click)="deleteExpenseEntry($event, entry.id)">Delete</a></td> </tr> </tbody> </table>
在这里,我们包含了另外两列。一列用于显示编辑链接,另一列用于显示删除链接。
更新ExpenseEntryListComponent中的deleteExpenseEntry方法,如下所示
deleteExpenseEntry(evt, id) { evt.preventDefault(); if(confirm("Are you sure to delete the entry?")) { this.restService.deleteExpenseEntry(id) .subscribe( data => console.log(data) ); this.getExpenseItems(); } }
在这里,我们要求确认删除,如果用户确认,则调用支出服务中的deleteExpenseEntry方法来删除所选支出项目。
将ExpenseEntryListComponent模板顶部的编辑链接更改为添加链接,如下所示:
<div class="col-sm" style="text-align: right;"> <button class="btn btn-primary" routerLink="/expenses/add">ADD</button> <!-- <button type="button" class="btn btn-primary">Edit</button> --> </div>
在ExpenseEntryComponent模板中添加编辑链接。
<div class="col-sm" style="text-align: right;"> <button type="button" class="btn btn-primary" (click)="goToList()">Go to List</button> <button type="button" class="btn btn-primary" (click)="goToEdit()">Edit</button> </div>
打开ExpenseEntryComponent并添加goToEdit()方法,如下所示:
goToEdit() { this.router.navigate(['/expenses/edit', this.selectedId]); }
更新AppComponent模板中的导航链接。
<!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top"> <div class="container"> <a class="navbar-brand" href="#">{{ title }}</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only" routerLink="/">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" routerLink="/expenses/add">Add Expense</a> </li> <li class="nav-item"> <a class="nav-link" routerLink="/about">About</a> </li> <li class="nav-item"> <div *ngIf="isUserLoggedIn; else isLogOut"> <a class="nav-link" routerLink="/logout">Logout</a> </div> <ng-template #isLogOut> <a class="nav-link" routerLink="/login">Login</a> </ng-template> </li> </ul> </div> </div> </nav> <router-outlet></router-outlet>
在这里,我们更新了添加支出链接和关于链接。
运行应用程序,输出将类似于如下所示:
尝试使用支出列表页面中的添加链接添加新的支出。输出将类似于如下所示
填写如下所示的表单:
如果数据填写不正确,验证代码将发出如下所示的警告:
单击提交。它将触发提交事件,数据将保存到后端并重定向到列表页面,如下所示:
尝试使用支出列表页面中的编辑链接编辑现有支出。输出将类似于如下所示:
单击提交。它将触发提交事件,数据将保存到后端并重定向到列表页面。
要删除项目,请单击删除链接。它将确认删除,如下所示:
最后,我们实现了应用程序中管理支出所需的所有功能。