【问题标题】:Use c# model class in angular在 Angular 中使用 c# 模型类
【发布时间】:2020-09-15 18:27:58
【问题描述】:

提前致谢

import { Component, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
  selector: 'app-fetch-data',
  templateUrl: './fetch-data.component.html'
})
export class FetchDataComponent {
  public forecasts: WeatherForecast[];
  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    http.get<WeatherForecast[]>(baseUrl + 'weatherforecast').subscribe(result => {
      this.forecasts = result;
    }, error => console.error(error));
  }
}
interface WeatherForecast {
  date: string;
  temperatureC: number;
  temperatureF: number;
  summary: string;
}

在上面的代码中,WeatherForecast 是一个在 angular .ts 文件中定义的接口。 如何使用现有的 C# 模型类而不是接口? 我无法使用 using 命令添加引用。 (如果写作格式有任何问题,请见谅)

【问题讨论】:

  • 您的要求似乎没有意义。它们是两种不同的语言。您不能在另一种语言中使用一种语言的代码。它们具有不同的语法,以及完全独立的编译器、运行时环境等。如果您需要能够以特定格式在它们之间发送数据,则最好用两种语言创建结构上相互匹配的类/对象。
  • 嗨,谢谢。那么我需要为相同的数据管理多个模型吗?
  • 是的,你知道。这是一个客户端-服务器架构。 Angular 在客户端上运行,C# 在服务器上运行。它们是独立的软件,在不同环境的不同机器上运行,它们之间没有链接,除了能够从一个到另一个发送消息(在这种情况下使用 HTTP)。
  • 您可以通过swagger等合约工具共享数据。我不确定角度需要什么。
  • 另一种方法是编写单独的 C++ 或 C# 节点模块。虽然这通常会带来更多的麻烦而不是它的价值。

标签: c# angular typescript asp.net-core model


【解决方案1】:
  1. 将您的 DTO 提取到单独的文件中
  2. 使用 Typegen https://typegen.readthedocs.io/en/latest/overview.html 或类似工具从带注释的 C# 类生成 DTO

【讨论】:

  • 这是唯一在这里分享模型的方法。你不能在 TS 中使用完全相同的类,但是你可以让你的 TS 接口自动保持同步,所以它实际上就像你在 TS 中有 C# 类一样
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-08
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
  • 2018-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多