angular - 将参数转换为内部类

标签 angular typescript

我在我的组件中定义了一个内部类来保存 View 模型,我需要将 http 响应接口(interface)转换为这个 View 模型。我试过这种方式:

@Component({
  selector: 'app-tasklist-items-grid',
  templateUrl: './tasklist-items-grid.component.html',
  styleUrls: ['./tasklist-items-grid.component.scss'],
  providers: [TasklistItemsService, BsModalService]
})
export class TasklistItemsGridComponent implements OnInit {

// .....

  TaskListItemViewModel = class {    
    id?: number;
    tasklistId: number;
    typeOfTask: number;
    statusId: number;
    created_at: Date;
    updated_at: Date;
    checked: Boolean;
    rowVersion: number;
  }

  convertToViewModel = (item: TaskListItemViewModel) => item;
}

但是,未找到 TaskListItemViewModel 类型。我也尝试过将内部类和方法都定义为静态的,但仍然没有用。

我错过了什么?

最佳答案

我认为您可以在组件外部声明模型的接口(interface),并在组件内部创建实现该接口(interface)的嵌套类(也称为类表达式)。然后您可以在类表达式中添加您的方法。

import { Component } from '@angular/core';

export interface MyInterface {
  id?: number;
  tasklistId: number;
  typeOfTask: number;
  // other properties
}
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  TaskListItemViewModel = class implements MyInterface {
    constructor(
      public id: number,
      public tasklistId: number,
      public typeOfTask: number
    ) {}
    // other methods which you want to implement
  }

  convertToViewModel = (item: MyInterface) => new this.TaskListItemViewModel(1, 2, 3);
}

当然这个例子展示了 TypeScript 的强大(在这个例子中我们看到了 Class expressions feature ),但我不会在实际项目中这样做,因为大多数流行的样式指南建议声明类/接口(interface)/枚举.. .(又名模型)在单独的文件中,通常是 some-feature.model.ts。然后我们可以在应用程序的其他部分使用我们的模型,例如组件、指令等。

关于angular - 将参数转换为内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52007938/

相关文章:

javascript - 如何使用 TypeScript/Angular 自定义我的 XLSX?

angular - 尝试对 Angular 模板进行 lint 时出现 ESLint 错误

node.js - 防止发送ts文件

typescript - 如何声明一个在 Typescript 中抛出错误的函数

javascript - 在 angularjs 中注册服务(使用 typescript )

node.js - 如何在一个文件中导入所有类并从那里使用它们 typescript

angular - 在 Promise 中返回 Observable

html - colspan 未应用于表的列

javascript - Angular 元素中的 CSS 不适用,除非放在/src 目录中

javascript - 当手指稍微移动时,点击事件不会在触摸屏上触发