我在我的组件中定义了一个内部类来保存 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/