Angular 2模型:接口与类

Tom*_*kas 7 typescript angular

我有一个登录/注册模块,我想为他们写一个模型.

我会使用接口,但我需要一个预定义的值.

我想知道 - 我应该将预定义的输出作为常量(它不会被更改,更改)并使用接口.或者将其写为类(如当前)

目前,我写了两个单独的类 - 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'
  ) { }
}
Run Code Online (Sandbox Code Playgroud)

Alu*_*dad 1

我肯定会使用接口。这是一种简单的方法,并遵循使用 JSON 的 TypeScript 建议。

涉案房产,

private connection = 'Username-Password-Authentication';
Run Code Online (Sandbox Code Playgroud)

可以由执行请求的服务很好地添加。

这也将减少代码重复,因为您可以使用通用函数或服务来创建此请求对象。

例如:

export default function withRequiredAuthProps<T>(model: T) {
  return {...model, connection: 'Username-Password-Authentication'};
}
Run Code Online (Sandbox Code Playgroud)

然后,将模型发送回服务的 Http 服务可以使用类型约束来验证在发出请求之前是否已添加该属性

例如:

export default class MyHttpClient {
  post<T extends {connection: 'Username-Password-Authentication'}>(url: string, body: T) {
    //...
  }
}
Run Code Online (Sandbox Code Playgroud)

这些仅作为示例,但它们基于最少且有效的代码。