我有一个登录/注册模块,我想为他们写一个模型。
我会使用接口,但我需要有一个预定义的值。
我想知道--我是否应该把预定义作为一个常量(它不会被改变,改变)并使用接口。或者把它写成类(就像现在一样)
目前,我编写了两个独立的类- registration.model.ts,login.model.ts,我可以抽象为只使用一个模型吗?(示例: user.model.ts)
下面是一些例子:
export class LoginUser {
constructor(
private email,
private password,
// I need to have it, backend expects it to be sent
private connection = 'Username-Password-Authentication'
) { }
}
export class RegistrateUser {
constructor(
public name: string,
public lastName: string,
public email: string,
public password: string,
// I need to have it, backend expects it to be sent
private connection = 'Username-Password-Authentication'
) { }
}发布于 2017-05-06 00:18:44
我肯定会使用接口。这是一种简单的方法,并且遵循TypeScript关于使用JSON的建议。
有问题的财产,
private connection = 'Username-Password-Authentication';可以由执行请求的服务很好地添加。
这还将减少代码重复,因为您可以使用通用函数或服务来创建此请求对象。
例如:
export default function withRequiredAuthProps<T>(model: T) {
return {...model, connection: 'Username-Password-Authentication'};
}然后,将模型发送回服务的Http服务可以在发出请求之前使用类型约束来验证属性是否已添加。
例如:
export default class MyHttpClient {
post<T extends {connection: 'Username-Password-Authentication'}>(url: string, body: T) {
//...
}
}这些只是作为示例,但它们是基于最少的代码,并且可以正常工作。
发布于 2017-06-07 18:57:16
恰巧遇到了你的问题&正在调查同样的事情。
关于Angular 2 Style docs here,“指导方针”是不实现一个接口,前提是一个类本身可以:
将class-implementing-interface用作接口(如果使用关键字而不是
作为一个经验法则:
Angular Guidelines > Typescript Guidelines (在Angular 2项目中)。
希望这对你有所帮助!:)
https://stackoverflow.com/questions/43809031
复制相似问题