在本文中,我将演示如何使用 Angular 作为前端构建 ASP.NET Core Web 应用程序。在过去的几年里,Angular 和 ASP.NET Core 都提供了一些很大的改进。在本文中,我们将学习如何使用这两种技术使用实体框架构建 Web 应用程序。
架构
使用 ASP.NET Core 和 Angular 构建的任何 Web 应用程序的架构概述可以如下所示,并且可以按如下方式构建。我们将拥有一个可以为我们的 Web 应用程序提供服务的 ASP.NET Core 后端。该 API 将允许用户执行 CRUD 操作。检索到的数据将存储在服务器上的数据库中以便持久保存,最终它们可以使用实体框架进行存储。API 可以让我们为用户添加的所有数据提供服务。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace MessageApplication.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class MessagesController : ControllerBase
{
public IEnumerable<Models.Message> Get()
{
return new Models.Message[]
{
new Models.Message
{
Owner = "John",
Text = "Hello"
},
new Models.Message
{
Owner = "Tim",
Text = "Hi"
}
};
}
}
}
为了发送消息列表,我们必须创建一个模型类,其中包含指定消息及其发件人的属性。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MessageApplication.Models
{
public class Message
{
public string Owner { get; set; }
public string Text { get; set; }
}
}
现在让我们更新 Angular,以便从服务而不是本地数组显示数据。我们将向我们新创建的 Web 服务发送对我们的消息的请求,因此为此创建一个 angular 服务。
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import { Injectable } from '@angular/core';
@Injectable()
export class WebService{
constructor(private http: HttpClient){}
getMessages(){
return this.http.get('https://localhost:44369/api/Messages').toPromise();
}
}
现在为了显示消息,我们需要首先运行服务器,即 ASP.NET Core 应用程序,我们将从中检索消息及其发件人。
运行服务器后,我们可以看到上面的输出。这些消息将由 Angular 应用程序检索以显示在前端。
概括
在本文中,我创建了一个使用 Angular 作为前端和 ASP.NET Core 作为后端的消息传递应用程序。在应用程序中,我们使用 ASP.NET Core 创建控制器,该控制器将有一个路由,为我们的前端提供我们的消息。使用 Angular,我们访问服务器位置,检索消息数据并将其显示在前端。