2017-01-18 28 views
-3

我一直在四处搜寻,但我没有看到我正在寻找的答案。如果我的问题重复,请让我知道。正确的方法来创建打印对象

我想创建一个包含属性是自定义类型的typescript中的对象。

问题是我的服务器提供的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格式的地址。

谢谢你的时间!

+0

看来你错过了很多关于你在做什么和你想做什么的基本知识。没有办法给你的问题提供一个很好的答案。 – lexith

+0

你的意思是说url是另一个http调用来获取“地址”信息? – Ayyash

+0

@lexith你是对的,我从来没有做过任何前端的东西。我在angular.io上经历了一个例子,并试图创建一个CRUD应用程序。 – ericDaWang

回答

1

如果我假设你有关如何将服务器检索到的数据映射到本地打字对象的问题,一种方法是在类中创建一个静态方法来返回类的新实例,它需要一个类型为“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); 
    } 
} 
1

解析您从服务器检索的JSON然后将其分配给您的属性,如下面

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

注意是一个很好的做法是定义用于制作要求服务器单独的服务

+0

感谢你的回应!所以你的意思是在我从http回调中得到回应后,我应该再次使用url进行http呼叫以获取地址? – ericDaWang

+0

如果你想从地址获取数据,那么你应该这样做 –

相关问题