c# - AspNet Core with Angular - 我们是否需要创建所有实体的副本?
问题描述
我正在尝试使用 Aspnet Core 学习 Angular,并查看由 Visual Studio 2017 的默认 Angular 模板创建的项目。
控制器声明一个WeatherForecast
类并返回一个IEnumerable<WeatherForecast>
-
[HttpGet("[action]")]
public IEnumerable<WeatherForecast> WeatherForecasts()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
DateFormatted = DateTime.Now.AddDays(index).ToString("d"),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
});
}
public class WeatherForecast
{
public string DateFormatted { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }
public int TemperatureF
{
get
{
return 32 + (int)(TemperatureC / 0.5556);
}
}
}
然后,调用上述代码并显示的角度组件IEnumerable<WeatherForecast>
如下 -
export class FetchDataComponent
{
public forecasts: WeatherForecast[];
constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
http.get<WeatherForecast[]>(baseUrl + 'api/SampleData/WeatherForecasts')
.subscribe(result =>{ this.forecasts = result; }, error => console.error(error));
}
interface WeatherForecast
{
dateFormatted: string;
temperatureC: number;
temperatureF: number;
summary: string;
}
如您所见,WeatherForecast
该类被声明了两次——一次在 .net 后端,然后再次在 angular 组件中!
我的问题是 - 在使用 AspetCore 和 Angular 时,我们是否总是需要像WeatherForecast
类一样声明所有实体(或 ViewModel,以适用者为准)两次?如果是这样,这似乎是很多重复的工作,并且可能违反了 DRY?
解决方案
你别无选择。AspNetCore 和 Angular 是使用 2 种不同语言(C# 和 TypeScript)的 2 个不同框架。即使 Visual Studio 为您提供了为这两个项目创建 1 个解决方案的能力,您也应该将您的 AspNetCore 项目和 Angular 项目视为 2 个独立的系统。不要忘记您的 AspNetCore API 能够为您的 Angular 项目之外的其他 HTTP 客户端提供服务。
推荐阅读
- c++ - 如何在qt中禁用QComboBox的快捷方式?
- elasticsearch - 在elasticsearch中实现同义词相同的搜索结果
- javascript - Angular - 显示不同的页面(简单)
- android - 如何使用 ADB 命令连接到任何指定的 Wi-Fi 网络(SSID)
- asp.net-mvc - Asp Net MVC4 BundleConfig
- jquery - 列表中的 Href 链接在移动设备上不可点击
- html - Bootstrap4 使卡片标题高度相同
- python - 导致 TypeError 的 Lambda 函数:“int”对象不可迭代
- winapi - GetModuleInformation() 函数返回地址和大小信息
- sql - SQL - HAVING(执行与结构)