我正在开发一个应用程序,我使用 .Net Core 作为我的 API,SQL Server 作为数据库,Angular 作为 UI。我正在学习的课程没有提供太多解释他为什么这样做,所以我决定在谷歌搜索没有帮助后在这里发布几个问题。在 Angular 应用程序中,讲师使用 api-model(接口)使用 http 方法从服务中的 API 获取数据,然后在组件 .ts 文件中,他将可观察响应设置为要使用的 ui-model在模板中。
UI 和 API 模型是相同的。他基本上将 API 获取的数据放入 API 模型中,并将其转储到 UI 模型中以在模板中使用
当您说模型时,我假设您只是指为数据(类型、接口或类)定义模式。它们的主要目的是确保您作为开发人员不会犯错误。如果你定义了一个数据类型并且你试图访问一个不存在的属性,打字稿编译器会捕捉到这个。另一个例子是,如果您尝试对id
参数进行一些数学运算,编译器会告诉您这是一个字符串,而不是一个数字。
是的,你应该在两边都定义你的模式,否则你会到处犯这样的愚蠢错误。加上这种方式,您可以获得智能感知和代码完成。
至于接口和类的区别,typescript中定义数据类型的方式有以下三种:
类型
这只是一个定义了每个属性类型的对象类型。类型不支持继承,并且它们没有构造函数。
type Fruit = {
name: string;
color: string;
weight: number;
similarFruits: Fruit[];
decompose: () => RottenFruit;
};
接口
接口本质上与类型相同,但它们可以extend
相互关联,类可以implement
。
interface Fruit {
name: string;
color: string;
}
interface Banana extends Fruit {
eat: () => string;
}
class BigYellowBanana implements Banana {
name: string;
color: string;
eat: () => string;
constructor() {
this.name = 'Big Yellow Banana';
this.color = 'Yellow';
this.eat = () => 'mmmm banana';
}
}
课程
类完全是另一种蠕虫,因为它们具有面向对象语言的所有功能。最值得注意的是,可以使用new
关键字调用的构造函数。
class BigBanana extends SmallBanana implements Banana {
name: string;
color: string;
private eatMessage = 'mmmm banana';
constructor(color: string) {
this.color = color;
this.name = `Big ${color} Banana`;
}
eat() {
return this.eatMessage;
}
}
const greenBanana = new BigBanana('Green');
我为我愚蠢的例子道歉。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句