Angular和.NET Core Web API入门应用程序

622 篇文章 16 订阅
226 篇文章 4 订阅

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

这是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.csConfigureServices方法中,如下所示。这样我们就可以使用API​​项目中定义的连接字符串在SQL Server中创建数据库和表:

//add the db context with the connection string
            services.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; 
        }

        ...

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

"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);
            ...
        }

现在进入AngularUI项目。使用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 customers
    get(){
        this.http.get<ICustomer[]>(this.url).pipe(
            ).subscribe(result => {
                if (result)
                    //notify the Observers of the change
                    this.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 customer
            if (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中定义的,该组件使来自MaterialDialog组件的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...>

CustomerComponenthtml中,添加了bootstrapflexbox类,以使元素居中对齐并组织布局:

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

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值