【问题标题】:Angular typechecking using interface使用接口进行角度类型检查
【发布时间】:2021-05-13 06:56:35
【问题描述】:

如何对返回的响应进行严格的角度类型检查。

1.data.json 文件用于临时 api 目的

[
  {
    "name": "Someone 1",
    "comment": "comment 1",
    "line": "line 1"
  },
  {
    "name": "Someone 2",
    "comment": "comment 2",
    "line": "line 2"
  },
  {
    "name": 3,
    "comment": "comment 3",
    "line": "line 3"
  }
]
  1. 模型界面
export interface Model {
  name: number;
  comment: string;
  line: string;
}

3.服务类app.service.ts

export class AppService {
  constructor(private _http: HttpClient) {}

  private api = "../api/data.json";

  loadData(): Observable<Model[]> {
    return this._http.get<Model[]>(this.api);
    //.pipe(tap((data) => console.log("All:" + JSON.stringify(data))));
  }

  loadSingle(): Observable<Model> {
    return this.loadData().pipe(map((data: Model[]) => data[2]));
  }
}

4.component类app.component.ts

export class AppComponent implements OnInit {

  myvarArray: Model[];

  myvarSingleton: Model;

  constructor(private _appService: AppService) {}

  ngOnInit() {
    this._appService.loadData().subscribe((data) => {
      this.myvarArray = data;
    });

    this._appService.loadSingle().subscribe((data) => {
      this.myvarSingleton = data;
      console.log(data.name + ":" + data.comment);
    });
  }
}

5.app.component.html

<h1>Printing obj data</h1>
<ul *ngFor="let data of myvarArray">
  <li>{{ data.name }} -- {{ data.line }}</li>
</ul>

<h1>Printing Single data</h1>
<span>{{ myvarSingleton.name }}</span>

什么是实现严格类型检查的方法,以便 data.json 中的值符合接口中声明的类型? 我的观点是,虽然当数据返回到 app.component 时,名称是以数字形式给出的,但它在编译时仍然不会显示任何错误,如果有某种方法可以隐式地检查这个而不是显式的验证函数?

[编辑] 另外,当在界面中明确定义了属性(但数据在页面上正确显示)时,为什么我会收到 myvarSingleton.name 上的未定义属性错误?为什么要调用 3 次?

console shows error saying name is undefined

【问题讨论】:

  • Typescript 是一种静态类型检查功能。在运行时 JavaScript 没有“严格”的类型检查。您需要编写代码以满足您的要求。
  • 您好!为了将来参考,当您跳过问题本身的代码而不是屏幕截图时,我们可以更轻松地提供帮助。
  • 能否请您添加源代码而不是图像?这将是一个伟大的!
  • 格式化代码

标签: javascript angular typescript web frontend


【解决方案1】:

您无法使用 TypeScript 验证 JSON.parse。你只能告诉 TS 你的 JSON 应该是什么。一种解决方法是创建一个像这样的验证函数,例如:

function isModel(arg: any): arg is Model {
  return arg 
  && (arg.name && typeof (arg.name) == 'string')
  && (arg && arg.comment && typeof (arg.comment) == 'string');
}

请注意,类型检查是硬编码的。如果它给您带来更多优势,您可能希望将 JSON 转换为类而不是使用接口。

【讨论】:

  • 我更多地考虑从编译时错误中节省的接口行。但我想在 json 响应的情况下,除了编写显式验证函数之外别无他法。 谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-13
  • 2018-10-30
  • 1970-01-01
  • 2016-04-20
  • 2020-06-07
  • 2020-03-20
相关资源
最近更新 更多