角度和打字稿中的模型.类、子类和接口



On 和 Angular 7/Typescript 服务 我正在调用一个返回的 GetTopPosts API 方法:

"result": [
  {
    "id": 1,
    "title": "History of Design",
    "category": {
      "id": 3,
      "name": "design"
    }
  },
  {
    "id": 2,
    "title": "Angular",
    "category": {
      "id": 4,
      "name": "code"
    }
  }
]

我的后端上生成每个帖子的模型是响应:

public class GetTopPostsModel {
  public class Response {  
    public Int32 Id { get; set; }
    public String Title { get; set; }  
    public CategoryModel Category { get; set; }
    public class CategoryModel {
      public Int32 Id { get; set; }
      public String Name { get; set; }
    }
  }
}

如何将GetTopPostsModel翻译成Typescript?

  1. 我应该使用接口还是类?
  2. 可以使用子类,例如,CategoryModel 是 Response 的子类,它是 GetTopPostsModel 的子类

注意

在TypeScript中,我定义信封如下:

export class Envelope<T> {
  result: T[];
  constructor(result: T[]) {
    this.result = result;
  }
}

你可以把它翻译为

export interface Response {
    public number Id;
    public string Title;  
    public Category category
}
export interface Category {
      public number id;
      public string name;
    }

并使用 Angular http 服务来获取它:

import { HttpClient } from "@angular/common/http"
public getLatest(): Observable<Response[]> {
    return this.http.get<Response[]>("api/latest");
}

当实体来自 REST 服务(而不是直接创建)时,可以使用接口。请记住,打字稿会被遍历,类型信息会丢失。

因此,对象的形状是唯一重要的事情:声明接口的所有字段和方法的对象可以被视为实现该接口的"true"对象。当您来自像 C# 这样的强类型语言时,这有点奇怪。

考虑到这一点,"子类"的概念变成了"具有相同的形状"。

我相信在您

的情况下,最好的方法是将对象转换为接口ITopPosts,因此在您的服务中,您将执行以下操作:

getTopPosts() {
  // now returns an Observable of ITopPosts
  return this.http.get<ITopPosts>(this.configUrl);
}

在使用请求的组件中,您将能够检查返回的数据是否符合您的要求,如下所示:

topPosts: ITopPosts;
showTopPosts() {
  this.topPostService.getTopPosts()
    .subscribe((data: ITopPosts) => this.topPosts= { ...data });
}

Typescript 中的接口可以使用与您提到的子类类似的方法,如下所示:

interface IInterface {
  myDate: IAnotherInterface
}
interface IAnotherInterface {
  something: myEnum
}
enum myEnum {
  1 = 'One',
  2 = 'Two'
}

TypeScript 不是一种基于类的语言,它使用原型,所以你最好使用接口

在此处阅读更多内容

根据您的要求,您正在寻找这样的东西:

export interface GetTopPostModel{
  response: Response;
}
export interface Response{
    id: number;
    title: string;
    category: Category
}
export interface Category {
      id: number;
      name: string;
}

最新更新