• 下载源160.2 KB

您可以在此处查看此项目的源代码和最新更新

这是Angular/.NET Core Web API入门应用程序,具有添加、编辑和删除客户的基本功能,因此您可以将其用作构建应用程序的起点。它使用以下框架:

  • Angular Material
  • Bootstrap
  • .NET Core
  • Entity Frameworks

如何在电脑上运行

请确保首先安装以下组件:

  • 节点v12.19。*
  • Angular CLI 10.2。*
  • .NET Core 3.1

在下载的代码中,打开文件api/Api/appsettings.Development.json并将数据源更改为指向您的SQL Server:

"AngApiStarterConn": "Data Source=YourServerNameHere;
Initial Catalog=AngApiStarter;Integrated Security=True;"

生成API解决方案以确保已安装NuGet软件包,并且该解决方案成功生成。您必须先成功构建解决方案,然后才能为数据库运行Entity Framework更新。

打开命令提示符并导航到api/Data,然后运行以下命令,该命令将使用应用程序所需的结构更新SQL Server:

dotnet ef database update -s ..\Api\Api.csproj

您现在应该拥有一个名为AngApiStarter的数据库,该数据库具有一个在SQL Server中命名为Customers的表。您可以将带有下面的SQL的示例插入customer表中:

insert into customers(firstName, lastName)
values('John', 'Smith');

通过运行API项目并检查以下URL,检查API是否可以从数据库获取数据:URL应该返回数据库中的customers列表:

https://localhost:44381/api/customer

导航至命令提示符下的ui文件夹,然后运行以下命令以获取运行Angular所需的库:

npm update

如果遇到找不到模块的错误,则可以运行以下命令以获取所需的模块:

npm install

通过运行以下命令来启动Angular,它将启动服务器并在浏览器中打开应用程序:

ng serve --open

应用程序的构建方式

从API的数据层开始,创建了Customer的类模型:

public class Customer{[Required]public int CustomerId { get; set; }[Required, StringLength(80)]public string FirstName { get; set; }[Required, StringLength(80)]public string LastName { get; set; }}

然后为Customer类创建DbContext,使用Customer类作为DbSet,其最终将成为数据库中的表:

public class AngApiStarterDbContext : DbContext{public DbSet<Customer> Customer { get; set; }public AngApiStarterDbContext(DbContextOptions<AngApiStarterDbContext> options): base(options){}}

然后,在API项目中,我们定义数据库连接字符串,并将以下代码添加到Startup.cs的ConfigureServices方法中,如下所示。这样我们就可以使用API​​项目中定义的连接字符串在SQL Server中创建数据库和表:

//add the db context with the connection stringservices.AddDbContextPool<AngApiStarterDbContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("AngApiStarterConn")));

生成解决方案,然后使用命令提示符,导航到Data项目文件夹,然后运行以下命令以创建数据库迁移的类:

dotnet ef migrations add initialCreate -s ..\Api\Api.csproj

创建类之后,运行以下命令以在SQL Server中创建数据库和表:

dotnet ef database update -s ..\Api\Api.csproj

在Data项目中,它具有接口以及使用实体框架的接口实现:

public interface ICustomerData{Task<IEnumerable<Customer>> Get();Task<Customer> GetCustomerById(int id);Task<Customer> Update(Customer customer);Task<Customer> Add(Customer customer);Task<int> Delete(int customerId);}
public class SqlCustomerData : ICustomerData{public AngApiStarterDbContext DbContext { get; }public SqlCustomerData(AngApiStarterDbContext dbContext){DbContext = dbContext;}...}

现在进入API项目。在API项目中,它在ConfigureServices方法中定义接口的实现类:

services.AddScoped<ICustomerData, SqlCustomerData>();

然后,控制器也通过依赖注入使用该接口:

public class CustomerController : ControllerBase{public ICustomerData CustomerData { get; }public CustomerController(ICustomerData customerData){CustomerData = customerData; }...

由于API和UI将在不同的网站上运行,因此需要允许UI网站使用CORS访问API。在API的appsettings.Development.json,它具有UI的url:

"CorsUrl": "http://localhost:4200"

然后在Startup.cs文件中指定CORS策略:

private readonly string corsPolicy = "defaultPolicy";public void ConfigureServices(IServiceCollection services){services.AddCors(options =>{options.AddPolicy(corsPolicy,builder =>{builder.WithOrigins(Configuration["CorsUrl"]).AllowAnyMethod().AllowAnyHeader().AllowCredentials();});});...}public void Configure(IApplicationBuilder app, IWebHostEnvironment env){...app.UseCors(corsPolicy);...}

现在进入Angular的UI项目。使用Angular入门项目,在项目app/common/material.module.ts下定义了Angular Materials组件,在其中添加了所有组件,以便您可以使用这些组件而无需将其显式添加到app.module.ts。然后在app.module.ts,它仅包含Material模块:

import { MaterialModule } from './common/material.module';

API URL的位置在environment/environments.ts文件中定义:

export const environment = {production: false,apiCustomer: 'https://localhost:44381/api/customer'
};

该模型在model/ICustomer.ts文件中定义,具有与API相同的模型签名:

export interface ICustomer{customerId: number,firstName: string,lastName: string
}

与API交互的支持位于service/customer.service.ts文件中。它使用BehaviorSubject将客户列表作为Observable(可以将其视为数据流)。当Observable改变时,所有的观察员(你可以把它当作听众或用户)得到通知的变化,可以相应地做出反应。在CustomerService类中,需要在Observable需要通知所有观察者时调用customerList.next方法:

private customerList = new BehaviorSubject<ICustomer[] | null>(null);customerList$ = this.customerList.asObservable();...//get the list of customersget(){this.http.get<ICustomer[]>(this.url).pipe().subscribe(result => {if (result)//notify the Observers of the changethis.customerList.next(result)});}

Customer组件显示了您可以管理的客户列表,它通过在ngOnInit方法中订阅CustomerService类来监听类中的更改:

export class CustomerComponent implements OnInit {...ngOnInit(){this.custService.customerList$.subscribe(data =>this.customerList = data);}

当用户单击“添加或“编辑客户按钮时,它将打开一个对话框,您可以将数据传递给该对话框,并定义关闭该对话框时要执行的操作。下面显示了添加一个新的customer并在关闭对话框时调用CustomerService时传递给该对话框的数据:

openAddDialog(){let dialogRef = this.custDialog.open(CustomerDialog, {width: '300px',data: {action: 'add',customer: { customerId: 0, firstName: '', lastName: ''}} });dialogRef.afterClosed().subscribe(result => {//add the customerif (result)this.custService.add(result)    });}

为了进行编辑customer,它需要将customer数据的副本而不是实际的customer数据传递给对话框,因此,如果用户决定取消,则customer值不会更改:

customer: {...customer} //shallow copy the customer using spread operator

对话框组件是在app/customer/dialog/customer-dialog.component.ts中定义的,该组件使来自Material的Dialog组件的MAT_DIALOG_DATA接受调用者的数据:

export class CustomerDialog {...constructor(public dialogRef: MatDialogRef<CustomerDialog>,@Inject(MAT_DIALOG_DATA) public data: any) {this.action = data.action;this.customer = data.customer;}

最后,使用npm添加bootstrap库,并将对bootstrap样式表的引用添加至index.html

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap...>

在CustomerComponent的html中,添加了bootstrap的flexbox类,以使元素居中对齐并组织布局:

<div class="d-flex flex-row justify-content-center"><div class="d-flex flex-column">

就这样。希望您觉得它对您的项目有帮助。

Angular和.NET Core Web API入门应用程序相关推荐

  1. ASP.NET Core Web API下事件驱动型架构的实现(二):事件处理器中对象生命周期的管理

    在ASP.NET Core Web API下事件驱动型架构的实现(一):一个简单的实现中,我介绍了事件驱动型架构的一种简单的实现,并演示了一个完整的事件派发.订阅和处理的流程.这种实现太简单了,百十行 ...

  2. ASP.NET Core Web API + Identity Server 4 + Angular 6 实战小项目视频

    今天开始尝试录制ASP.NET Core Web API的教学视频. 这是一个小项目的实战视频, 该项目采用了: ASP.NET Core 2.1 做API Identity Server 4 Ang ...

  3. ASP.NET Core Web API 索引 (更新Identity Server 4 视频教程)

    GraphQL 使用ASP.NET Core开发GraphQL服务器 -- 预备知识(上) 使用ASP.NET Core开发GraphQL服务器 -- 预备知识(下) [视频] 使用ASP.NET C ...

  4. 如何测试ASP.NET Core Web API

    在本文中,我们将研究如何测试你的ASP .NET Core 2.0 Web API解决方案.我们将了解使用单元测试进行内部测试,使用全新的ASP .NET Core的集成测试框架来进行外部测试. 本文 ...

  5. 如何测试 ASP.NET Core Web API

    在本文中,我们将研究如何测试你的 ASP .NET Core 2.0 Web API 解决方案.我们将了解使用单元测试进行内部测试,使用全新的 ASP .NET Core 的集成测试框架来进行外部测试 ...

  6. ASP.NET Core Web API + Ng6 实战视频 Day 2

    第一天课程: ASP.NET Core Web API + Identity Server 4 + Angular 6 实战小项目视频 Day 2 第一部分: Day 2 第二部分: 视频专辑持续更新 ...

  7. Asp.Net Core Web Api的简单实例

    文章目录 WebApi 第一个Asp.NetCoreWebApi程序 传入的参数 返回的返回值 WebApi和EF Core的联用 总结 WebApi Web API是网络应用程序接口.包含了广泛的功 ...

  8. 针对ASP.NET Core Web API的先进架构

    \ 本点要点 \\ 与传统的ASP.NET相比,ASP.NET Core的新架构提供了一些好处\\t ASP.NET Core从一开始就包含对依赖注入的支持\\t 单一职责原则简化了实施和设计.\\t ...

  9. ASP.NET Core Web APi获取原始请求内容

    前言 我们讲过ASP.NET Core Web APi路由绑定,本节我们来讲讲如何获取客户端请求过来的内容. ASP.NET Core Web APi捕获Request.Body内容 [HttpPos ...

最新文章

  1. eclipse 切换svn账号
  2. 11. java 抽象类
  3. Win2000 DDK 附带例子概览(图解)
  4. Oracle经典教程学习笔记
  5. Linux chmod命令小贴士
  6. CMake基础 第1节 初识CMake
  7. MongoDB学习笔记(三)使用Spring Data操作MongoDB
  8. CF641D. Little Artem and Random Variable
  9. 如何把html转换cad,Tab2Xls插件(捷克版)将AutoCAD表格转换为XLS、CSV或HTML。
  10. go 是常驻内存吗_关于常驻内存RES,pprof,heap,threadcreate的疑问
  11. python语言接收信息的内置函数_python接收信息的内置函数是
  12. liferay+portlet+开发实例
  13. dbeaver 视图有一个x_《工程制图》——视图、剖视图、断面图、局部放大图
  14. NLP系列之文本分类
  15. 基坑监测日报模板_基坑水平监测日报表
  16. 规则引擎系列—初识规则引擎
  17. HSV肤色侦测法去除背景
  18. 技术管理者对知识组织的认识
  19. “数据”到底是资产还是负债?
  20. 白杨英语-字母含义笔记

热门文章

  1. python 类初始化参数校验_python之类的任意数量参数初始化
  2. 家族关系查询系统程序设计算法思路_七大查找算法(附C语言代码实现)
  3. 数据可视化demo_火出圈的大屏你真的会做吗?这才是老板最爱的可视化大屏
  4. python字符串_Python字符串格式化%s%d%f详解
  5. Neumorphism新拟物化控件设计灵感
  6. 百搭手绘卡通牛年吉祥生肖素材,萌到心里的小牛
  7. 设计灵感|春节新年到!充满年味的海报给你参考
  8. 炫彩渐变海报版式海报
  9. 设计师交流社区,让你的原创设计作品展示给世界
  10. UI设计素材模板|wireframe线框图设计要点