2017-02-27 58 views
0

我試圖查詢將以非常不友好的格式返回JSON的w API API。Angular忽略實例化對象上的JSON字段

{ 
    "id": 3, 
    "meta": { 
     "type": "home.HomePage", 
     "detail_url": "http://localhost:8000/api/v1/pages/3/" 
    }, 
    "parent": null, 
    "title": "Homepage", 
    "body": "<h2>cool an h2 fgf</h2>", 
    "main_image": { 
     "id": 1, 
     "meta": { 
      "type": "wagtailimages.Image", 
      "detail_url": "http://localhost:8000/api/v1/images/1/" 
     } 
    }, 
    "header_image": { 
     "id": 1, 
     "meta": { 
      "type": "wagtailimages.Image", 
      "detail_url": "http://localhost:8000/api/v1/images/1/" 
     } 
    }, 
    "show_in_menus": true, 
    "full_url": "/media/images/Background-4.original.jpg" 
} 

我真正的希望是這樣的一類。

export class HomePage { 
    id: number; 
    title: string; 
    body: string; 
    full_url: string; 

} 

但是,無論何時我從服務中取回數據並嘗試記錄它,它都是未定義的。

有沒有什麼辦法可以讓我忽略打字稿中JSON不想要的字段?

我使用的服務是:

import { Injectable } from '@angular/core'; 
import {Http, Response} from '@angular/http'; 
import {Observable} from "rxjs"; 
import {HomePage} from "./HomePage"; 

@Injectable() 
export class HomePageService { 

    constructor(private http: Http){ 
    } 

    getHomePage(GUID: number): Observable<HomePage>{ 
    return this.http 
     .get("http://localhost:8000/api/v1/pages/" + GUID + "/") 
     .map(this.extractData) 
     .catch(this.handleError); 
    } 
    private extractData(res: Response) { 
    let body = res.json(); 
    return body.data || {} 
    } 
    private handleError (error: Response | any) { 
    // In a real world app, we might use a remote logging infrastructure 
    let errMsg: string; 
    if (error instanceof Response) { 
     const body = error.json() || ''; 
     const err = body.error || JSON.stringify(body); 
     errMsg = `${error.status} - ${error.statusText || ''} ${err}`; 
    } else { 
     errMsg = error.message ? error.message : error.toString(); 
    } 
    console.error(errMsg); 
    return Observable.throw(errMsg); 
    } 
} 

和組件:

import {Component, OnInit, OnDestroy} from '@angular/core'; 
import {HomePageService} from './home-page.service'; 
import {ActivatedRoute} from '@angular/router'; 
import {HomePage} from "./HomePage"; 

@Component({ 
    selector: 'app-home-page', 
    templateUrl: './home-page.component.html', 
    styleUrls: ['./home-page.component.css'], 
    providers: [HomePageService] 
}) 
export class HomePageComponent implements OnInit, OnDestroy{ 
    id: number; 
    private sub: any; 
    public homePage: HomePage; 
    errorMessage: string; 
    constructor(private homePageService : HomePageService, private route: ActivatedRoute) { 

    } 

    ngOnInit() { 
    this.sub = this.route.params.subscribe(params => { 
     this.id = +params['id']; 
    }); 
    this.homePageService.getHomePage(this.id) 
     .subscribe(
     homePage => this.homePage = new HomePage(homePage), 
     error => this.errorMessage = <any>error, 
     () => console.log(this.homePage.full_url) 
    ); 
    console.log(this.id); 
    } 
    ngOnDestroy() { 
    this.sub.unsubscribe(); 
    } 

} 
+0

你能爲正在獲取數據的服務添加代碼嗎? – eminlala

+0

添加了組件和服務代碼,謝謝。 –

+0

'homePage => this.homePage = new HomePage(homePage)''你有'HomePage'類的構造函數嗎? – eminlala

回答

1

homePage => this.homePage = new HomePage(homePage) - 在你的代碼,我沒有看到HomePage類中定義的構造函數。所以當你將homePage對象傳遞給它時,沒有任何反應。試試這個:

export class HomePage{ 
    id: number; 
    title: string; 
    body: string; 
    full_url: string; 

    constructor(homePageObj: any) 
    { 
     if (homePageObj) 
     { 
      this.id = homePageObj.id; 
      this.title = homePageObj.title; 
      this.body = homePageObj.body; 
      this.full_url = homePageObj.full_url; 
     } 
    } 
} 
+0

嗨,謝謝你,但它沒有奏效。 homePageObj沒有填充任何東西。老實說,我認爲構造函數在你定義類變量時會自動填充,就像Heroes示例中的那樣,它們不會像這樣填充構造函數。 –

+0

這裏的服務實際上存在問題。 return body.data || 需要爲{} 我剛剛從某處糟糕地複製了該代碼。不過,我相信這回答了我問的問題。當參數與正確的響應正文不匹配時,您將需要angular會引發錯誤,您應該手動定義構造函數。謝謝 –

+0

你可以嘗試的另一件事是'return body.data || {}'。 – eminlala