- Angular 教程
- Angular - 首页
- Angular - 概述
- Angular - 特性
- Angular - 优点与缺点
- Angular 基础
- Angular - 环境搭建
- Angular - 第一个应用
- Angular - MVC 架构
- Angular 组件
- Angular - 组件
- Angular - 组件生命周期
- Angular - 视图封装
- Angular - 组件交互
- Angular - 组件样式
- Angular - 嵌套组件
- Angular - 内容投影
- Angular - 动态组件
- Angular - 元素
- Angular 模板
- Angular - 模板
- Angular - 文本插值
- Angular - 模板语句
- Angular - 模板中的变量
- Angular - SVG 作为模板
- Angular 数据绑定
- Angular - 数据绑定及类型
- Angular - 数据绑定
- Angular - 事件绑定
- Angular - 属性绑定
- Angular - 属性绑定
- Angular - 类和样式绑定
- Angular 指令
- Angular - 指令
- Angular - 内置指令
- Angular 管道
- Angular - 管道
- Angular - 使用管道转换数据
- Angular 依赖注入
- Angular - 依赖注入
- Angular HTTP 客户端编程
- Angular - 服务
- Angular - HTTP 客户端
- Angular - 请求
- Angular - 响应
- Angular - GET 请求
- Angular - PUT 请求
- Angular - DELETE 请求
- Angular - JSON-P
- Angular - 使用 HTTP 进行 CRUD 操作
- Angular 路由
- Angular - 路由
- Angular - 导航
- Angular - Angular Material
- Angular 动画
- Angular - 动画
- Angular 表单
- Angular - 表单
- Angular - 表单验证
- Angular Service Workers & PWA
- Angular - Service Workers & PWA
- Angular 测试
- Angular - 测试概述
- Angular NgModule
- Angular - 模块介绍
- Angular 高级
- Angular - 身份验证与授权
- Angular - 国际化
- Angular - 可访问性
- Angular - Web Workers
- Angular - 服务器端渲染
- Angular - Ivy 编译器
- Angular - 使用 Bazel 构建
- Angular - 向后兼容性
- Angular - 响应式编程
- Angular - 指令和组件之间的数据共享
- Angular 工具
- Angular - CLI
- Angular 其他
- Angular - 第三方控件
- Angular - 配置
- Angular - 数据显示
- Angular - 装饰器和元数据
- Angular - 基本示例
- Angular - 错误处理
- Angular - 测试和项目构建
- Angular - 生命周期钩子
- Angular - 用户输入
- Angular - 最新动态?
- Angular 有用资源
- Angular - 快速指南
- Angular - 有用资源
- Angular - 讨论
Angular - 基本示例
在这里,我们将学习关于Angular的完整步骤工作示例。
让我们创建一个Angular应用程序来检查我们日常的支出。让我们选择ExpenseManager作为我们的新应用程序名称。
创建应用程序
使用以下命令创建新应用程序。
cd /path/to/workspace ng new expense-manager
这里:
new是ng CLI应用程序的一个命令。它将用于创建新的应用程序。它会问一些基本问题以便创建新的应用程序。让应用程序选择默认选项就足够了。关于如下提到的路由问题,请指定No。
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组件中使用。
providerIn选项及其值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**。
我们没有使用任何后端。相反,我们使用 Observable 模拟了 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 的 logout 方法。
- 注销用户后,页面将重定向到主页 (/)。
使用以下命令创建一个守卫:
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** 来保存(添加/更新)支出条目。
使用 Expense 服务添加和更新支出条目。
使用支出表单更新 **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 { }
在这里,我们添加了 **about、add expense** 和 **edit expense** 路由。
在 **ExpenseEntryListComponent** 模板中添加 **Edit** 和 **Delete** 链接。
<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** 模板顶部的 **Edit** 链接更改为 **Add** 链接,如下所示:
<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** 模板中添加 **Edit** 链接。
<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>
在这里,我们更新了 **add expense** 链接和 **about** 链接。
运行应用程序,输出将类似于以下所示:
尝试使用支出列表页面中的 **Add** 链接添加新的支出。输出将类似于以下所示
填写表单,如下所示:
如果数据未正确填写,验证代码将发出警报,如下所示:
单击 **Submit**。它将触发提交事件,数据将保存到后端并重定向到列表页面,如下所示:
尝试使用支出列表页面中的“编辑”链接编辑现有支出。输出将类似于以下所示:
单击 **Submit**。它将触发提交事件,数据将保存到后端并重定向到列表页面。
要删除项目,请单击删除链接。它将确认删除,如下所示:
最后,我们实现了在应用程序中管理支出所需的所有功能。