简体   繁体   English

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

[英]proper way to create a typescript object

I have been searching around, but I don't see the answer I'm looking for.我一直在四处寻找,但没有看到我正在寻找的答案。 Please let me know if my question is duplicated.如果我的问题重复,请告诉我。

I'm trying to create an object in typescript which contains attributes that are custom types.我正在尝试在打字稿中创建一个对象,其中包含自定义类型的属性。

The problem is my server provides the object with urls.问题是我的服务器为对象提供了 url。 I'm not sure how to deal with the mapping.我不确定如何处理映射。 Please excuse me if I'm not explaining this well.如果我没有很好地解释这一点,请原谅。 I'm kind of new to all these.我对所有这些都很陌生。 BTW I'm using Angular and Typescript顺便说一句,我正在使用 Angular 和 Typescript

Here is an example.这是一个例子。 The object is like:对象是这样的:

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

But, the json retrieved from my server is like:但是,从我的服务器检索到的 json 是这样的:

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

If I use the address url I should get the address in json format.如果我使用地址 url,我应该以 json 格式获取地址。

Thanks for your time!谢谢你的时间!

parse the json that you have retrieved from server then assign it to your properties like below解析您从服务器检索到的 json,然后将其分配给您的属性,如下所示

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

Note that a good practice is to define a separate service for making request to server请注意,一个好的做法是定义一个单独的服务来向服务器发出请求

If I assume your question about how to map server retrieved data to local typescript objects, one way of doing it is create a static method in class to return a New Instance of the class, it takes an object of type "any" and returns an object after mapping all properties.如果我假设您的问题是关于如何将服务器检索到的数据映射到本地打字稿对象,一种方法是在类中创建一个静态方法以返回类的新实例,它需要一个“any”类型的对象并返回一个映射所有属性后的对象。 Use that method after http request comes back, or after subscription, depends on your setup.在 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