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

时间:2017-01-18 16:28:15

标签: angular typescript

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

我正在尝试在typescript中创建一个包含自定义类型属性的对象。

问题是我的服务器提供了带url的对象。我不知道如何处理映射。如果我不解释这个问题,请原谅。我对这些都很陌生。顺便说一下,我正在使用Angular和Typescript

这是一个例子。对象如下:

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

但是,从我的服务器检索到的json就像:

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

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

谢谢你的时间!

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:1)

如果我假设您关于如何将服务器检索的数据映射到本地typescript对象的问题,一种方法是在类中创建一个静态方法以返回类的新实例,它采用类型为“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);
   }
}
相关问题