2016-10-16 81 views
7

我試圖找到將我的json對象投射到Typescript對象的最佳方法。 我有一個http獲取服務,它返回用戶列表。 我的當前版本的作品,我從JSON功能添加到我所有的模型類,使測繪工作:Angular2從JSON解析到對象

export class User { 

    constructor(
     public pk: number, 
     public username: string, 
     public first_name: string, 
     public last_name: string, 
     public email: string, 
     public profile: UserProfile,) { 
    } 

    static fromJSON(json: any): User { 
     let user = Object.create(User.prototype); 
     Object.assign(user, json); 
     user.profile = UserProfile.fromJSON(json.profile); 
     return user; 
    } 
} 

行之有效。但是我在角度2文檔中沒有找到。在英雄教程中,JSON自動鑄造反對這種方式:

getHeroes(): Observable<Hero[]> { 
    return this.http.get(this.heroesUrl) 
        .map(this.extractData) 
        .catch(this.handleError); 
    } 
    private extractData(res: Response) { 
    let body = res.json(); 
    return body.data || { }; 
    } 

我不能讓這個方法對我的情況下工作,我說,body.data是不確定的。 這個方法真的有效嗎?

編輯:

我的HTTP服務不返回用戶的數組。它返回一個頁面,該頁面在其'results'屬性中包含一組用戶。

{ 
    "count": 2, 
    "next": null, 
    "previous": null, 
    "results": [ 
    { 
     "pk": 48, 
     "first_name": "Jon", 
     "last_name": "Does", 
     "profile": { 
     "pk": 46, 
     "gender": "U" 
     } 
    }, 
    { 
     "pk": 47, 
     "first_name": "Pablo", 
     "last_name": "Escobar", 
     "profile": { 
     "pk": 45, 
     "gender": "M" 
     } 
    } 
    ] 
} 

我的服務代碼:

private extractData(res: Response) { 
    let body = res.json().results; 
    return body || {}; //<--- not wrapped with data 
    } 

    search(authUser: AuthUser, terms: string): Observable<User[]> { 
    let headers = new Headers({ 
     'Content-Type': 'application/json', 
     'X-CSRFToken': this.cookiesService.csrftoken, 
     'Authorization': `Token ${authUser.token}` 
    }); 
    let options = new RequestOptions({ headers: headers }); 
    return this.http.get(environment.server_url + 'user/?search=' + terms, options) 
     .map(this.extractData); 
    // .map((response: Response) => response.json()); 
    } 

我的搜索組件代碼:

onSearch(terms: string) {  
    this.searchService.search(this.user, terms).subscribe(
     response => {  
      console.log(response); // Return array of object instead of array of user 
     }, 
     error => { 
      console.log(JSON.stringify(error)); 
     }, 
    () => { } 
    ); 
} 

編輯2:

爲了使這種情況下更容易,我已經寫了這簡單的代碼:

test(){ 
    let json_text=` [ 
     { 
     "id": 1, 
     "text": "Jon Doe" 
     }, 
     { 
     "id": 1, 
     "text": "Pablo Escobar" 
     } 
    ]`; 

    console.log(<MyObject[]>JSON.parse(json_text)); // Array of objects 
    console.log(MyObject.fromJSON(JSON.parse(json_text))); // Array of 'MyObject' 
    } 



export class MyObject{ 
    id: number; 
    text: string; 

    static fromJSON(json: any): MyObject { 
     let object = Object.create(MyObject.prototype); 
     Object.assign(object, json); 
     return object; 
    } 
} 
  • console.log(<MyObject[]>JSON.parse(json_text))返回一個對象名單
  • console.log(MyObject.fromJSON(JSON.parse(json_text)))返回MyObject的

回答

2

的 名單這是因爲在角教程,JSON是在數據屬性。

正如在本教程

說毫無有關服務器API假設。並非所有服務器都返回帶有數據屬性的 對象。

如果你不與任何財產包裹你的JSON你可以使用

private extractData(res: Response) { 
    let body = res.json(); 
    return body || { }; //<--- not wrapped with data 
} 

更新:

組件代碼

onSearch(terms: string) {  
    this.searchService.search(this.user, terms).subscribe(
     (response: SearchResponse) => { // <--- cast here 
      console.log(response); 
     }, 
     error => { 
      console.log(JSON.stringify(error)); 
     }, 
    () => { } 
    ); 
} 
+0

謝謝。通過修改,它會返回一個「Object」列表,而不是「User」列表。有沒有辦法解決它? – Ben

+0

你可以添加你的服務代碼嗎? – Sefa

+0

我編輯了我的文章 – Ben