首页 > 解决方案 > 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?

标签: c#angularasp.net-core

解决方案


你别无选择。AspNetCore 和 Angular 是使用 2 种不同语言(C# 和 TypeScript)的 2 个不同框架。即使 Visual Studio 为您提供了为这两个项目创建 1 个解决方案的能力,您也应该将您的 AspNetCore 项目和 Angular 项目视为 2 个独立的系统。不要忘记您的 AspNetCore API 能够为您的 Angular 项目之外的其他 HTTP 客户端提供服务。


推荐阅读