2017-01-24 14 views
0

私はangular2の新機能です。ここで、getLeftData()の戻り値の型はどのようにして特定の戻り値の型になりますか?
Angular 2タイスクリプトでjsonオブジェクトのListの型を返す方法はありますか?

HTTPTestService.ts:

@Injectable() 
export class HTTPTestService { 
    private siteUrl="https://api.stackexchange.com/2.2/sites"; 
    constructor(private _http: Http) { } 
    getLeftData(): Promise<Items[]> { 
     return this._http.get(this.siteUrl). 
     toPromise() 
     .then(response =>response.json().data as Items[]) 
    } 
} 

JSONデータ:

{ 
    "items": [ 
    { 
     "aliases": [ 
     "http://www.xyz.in", 
     "http://facebook.xyz.in" 
     ], 
     "styling": { 
     "tag_background_color": "#E0EAF1", 
     "tag_foreground_color": "#3E6D8E", 
     "link_color": "#0077CC" 
     }, 
     "related_sites": [ 
     { 
      "relation": "meta", 
      "api_site_parameter": "meta.xyz", 
      "site_url": "http://met.xyz.in" 
     }, 
     { 
      "relation": "chat", 
      "name": "Stack Overflow Chat" 
     } 
     ], 
     "markdown_extensions": [ 
     "Prettify" 
     ], 
     "launch_date": 1221436800, 
     "closed_beta_date": 1217462400, 
     "site_state": "normal", 
     "favicon_url": "https://cdn.sstatic.net/Sites/xyz/img/favicon.ico", 
     "name": "Stack Overflow", 
     "site_type": "main_site" 
    } 
    ] 
} 

誰が助けるならば、どの角度2 typescriptですでJSONオブジェクトのリストの戻り値の型だろうか?

+0

あなたが代わりに約束の観測を使用する必要があります。これをチェックしてください投稿http://stackoverflow.com/questions/37364973/angular-2-promise-vs-observable – alltej

答えて

1

私はあなたの正確な問題が何かなり確実ではないけど、試してみましょう。..

まず:あなたべき「モデル」あなたItems級!

2番目:json().dataの代わりにjson().itemsを使用してください。

多分これは役立ちます:https://plnkr.co/edit/gdwI1XfsUDCgZgoaKjce?p=preview

export class ItemModel { 
    aliases: string[]; 
    styling: { 
    tag_background_color: string, 
    tag_foreground_color: string, 
    link_color: string 
    }, 
    related_sites: { 
    relation: string, 
    api_site_parameter: string, 
    site_url: string, 
    name: string 
    }[], 
    markdown_extensions: string[], 
    launch_date: number, 
    closed_beta_date: number, 
    site_state: string, 
    // ... 
    // ... 
    name: string, 
    // ... 
    // ... 
} 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <h2>Hello {{name}}</h2> 
     <p *ngFor="let item of _items">{{ item.name }}</p> 
    </div> 
    `, 
}) 
export class App { 
    name:string; 
    private _items: ItemModel[] = []; 

    constructor(private _http: Http) { 
    this.name = 'Angular2' 
    } 

    ngOnInit() { 
    this.getLeftData().subscribe(items => { 
     console.log(items); 
     this._items = items; 
    }); 
    } 

    public getLeftData(): Observable<ItemModel[]> { 
    return this._http 
     .get('https://api.stackexchange.com/2.2/sites') 
     .map(response => response.json().items); 
    } 
} 
+0

ありがとう、それは@ mxii –

関連する問題