繁体   English   中英

创建打字稿对象的正确方法

[英]proper way to create a typescript object

我一直在四处寻找,但没有看到我正在寻找的答案。 如果我的问题重复,请告诉我。

我正在尝试在打字稿中创建一个对象,其中包含自定义类型的属性。

问题是我的服务器为对象提供了 url。 我不确定如何处理映射。 如果我没有很好地解释这一点,请原谅。 我对所有这些都很陌生。 顺便说一句,我正在使用 Angular 和 Typescript

这是一个例子。 对象是这样的:

export class Contact { 
    name : string;
    address : {
        street : string;
        city : string;
    }
}

但是,从我的服务器检索到的 json 是这样的:

{
    "name" : "firstname lastname",
    "address" : "http://localhost:5000/contacts/001"
}

如果我使用地址 url,我应该以 json 格式获取地址。

谢谢你的时间!

解析您从服务器检索到的 json,然后将其分配给您的属性,如下所示

...
.subscribe(
data => {
  this.name = data.name
  this.address = data.adress
})

请注意,一个好的做法是定义一个单独的服务来向服务器发出请求

如果我假设您的问题是关于如何将服务器检索到的数据映射到本地打字稿对象,一种方法是在类中创建一个静态方法以返回类的新实例,它需要一个“any”类型的对象并返回一个映射所有属性后的对象。 在 http 请求返回后或订阅后使用该方法,取决于您的设置。

export class Address {
   constructor(public name:string, description: string){
    }
   public static NewInstance(address: any){
      //map here
      return new Address(address.db_name, address.address);
   }
}
export class Student {
    constructor(
        public name : string,
        public classes: StudentClass[],
        public address: Address
    ){

    }
     public static NewInstance(student: any){
         let studentclasses = student.classes.map(n => StudentClass.NewInstance(n));
         return new Student(student.firstname+' ' + student.lastname, studentclasses, Address.NewInstance(student.addresss));
    }

}
export class StudentClass {
   constructor(public: name: string);
   public static NewInstance(studentclass: any){
        return new StudentClass(studentclass.namefromdb);
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM