2016-04-19 30 views
2

我有这样的代码,其读取一些JSON数据:Angular2 HTTP显示JSON特定值

import {Component} from 'angular2/core'; 
import {Http, Response} from 'angular2/http'; 

@Component({ 
    selector: 'my-app', 
    template: ` 
     <h2>Basic Request</h2> 
     <button type="button" (click)="makeRequest()">Make Request</button> 
     <div *ngIf="loading">loading...</div> 
     <pre>{{data | json}}</pre> 

    ` 

}) 
export class AppComponent { 

    data: Object; 
    loading: boolean; 

    constructor(public http: Http) { 
    } 
    makeRequest(): void { 
     this.loading = true; 
     this.http.request('http://jsonplaceholder.typicode.com/photos/1') 
      .subscribe((res: Response) => { 
       this.data = res.json(); 
       this.loading = false; 
      }); } 

} 

This is the returned json: 

{ 
    "albumId": 1, 
    "id": 1, 
    "title": "accusamus beatae ad facilis cum similique qui sunt", 
    "url": "http://placehold.it/600/92c952", 
    "thumbnailUrl": "http://placehold.it/150/30ac17" 
} 

{{data | json}}正在返回的所有数据。

我想只拿到标题为例。 所以我试过这个:

{{data.title | json}}但这是行不通的。

显示标题的正确方法是什么?

回答

6

使用Elvis操作符这样

<pre>{{data?.title}}</pre> 

Elvis运算符(?)表示数据字段是可选的,如果未定义,则应忽略表达式的其余部分。

0

数据是一个JSON对象,所以如果你使用数据然后使用| json管道。 如果你想使用的值不是一个对象,那么就使用值直接

{{data.title}} 
+0

这并不返回任何东西...编辑说:未解决的变量标题 – Satch3000

+0

我有同样的问题。只需在html代码中写入对象,就会在视图中打印“[object Object]”。尝试获取“异常:TypeError:l_fav0在[null]”中未定义的任何属性结果,其中“fav”是我的对象的名称。我不知道我错过了什么,但它与Satch3000的问题相同。整个网络只给出相同的建议,没有帮助,没有例子,除了太简单的例子。 –

3

添加地图,并切换到获得

this.data = {}; //initialize to empty object 
    this.http.get('http://jsonplaceholder.typicode.com/photos/1') 
      .map((res: Response) => res.json()) 
      .subscribe(res => { 
       this.data = res; 
       this.loading = false; 
      }); 

然后在模板中使用这样的{{data.title}}

这里有几个HTTP样本:http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http

+0

遗憾的是没有工作或者 – Satch3000

+0

这是数据:{ “ALBUMID”:1, “ID”:1, “称号”: “accusamus beatae广告facilis暨similique魁必须遵守”, “URL”:“HTTP ://placehold.it/600/92c952“, ”thumbnailUrl“:”http://placehold.it/150/30ac17“ } – Satch3000

+0

需要一张地图和一个获得通话 – TGH

0

你可以试试这个

this._http.request('http://jsonplaceholder.typicode.com/photos/1') 
      .map((res:Response) => res.json()) //add this line 
      .subscribe(
       data => this.myData = data, 
       this.loading = false; 
       error =>this.logError(error), 
      ); 

,你现在可以做{{myData.title}}

在超过一个对象使用:ngFor这样

<li *ngFor="let item of myData"> 
     {{item.title}} 
    </li>