简体   繁体   中英

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. 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

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:

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

If I use the address url I should get the address in json format.

Thanks for your time!

parse the json that you have retrieved from server then assign it to your properties like below

...
.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. Use that method after http request comes back, or after subscription, depends on your setup.

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);
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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