Angular 2 HTTP显示特定于JSON的值
Angular 2 HTTP display JSON specific values
我有这样的代码,它读取一些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}}
,但这不起作用。
只显示标题的正确方式是什么?
使用类似的elvis运算符
<pre>{{data?.title}}</pre>
Elvis运算符(?)表示数据字段是可选的,如果未定义,则应忽略表达式的其余部分。
添加地图并切换以获取
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
Data是一个JSON对象,因此如果使用数据,则使用|JSON管道。如果你想使用一个不是Object的值,那么直接使用
{{data.title}}
你可以试试这个
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 like this
<li *ngFor="let item of myData">
{{item.title}}
</li>
相关文章:
- 通过JSON中的值增加
- 更改返回的JSON数据的值
- 从json数组中查找满足条件的特定元素的值
- 如何在JSON中更改localStorage中键的值
- Javascript:获取 JSON 中的值计数
- 在json对象中查找关键字中的值
- 如何从下拉列表中的值在量角器中创建 json 字符串
- 如何使用 PHP 更新 JSON 文件中的值
- 对 JSON JavaScript 中的值应用折扣
- 当图像和链接是 json 对象属性的值时,它们不起作用
- Angular 2 HTTP显示特定于JSON的值
- 使用Angularjs根据json的值检查checkboxex
- 如何在 AngularJS 中显示来自 JSON 的值
- 本地存储的 json 数组正在打印,但来自 json 的值在 cordova 应用程序中给出未定义
- 如何保持之前发送到 JSON 的值
- 使用jQuery获取特定于JSON的值
- 为什么可以't我改变Json的值
- 如何在JSON的值部分使用Javascript变量
- 使用jquery删除和替换JSON的值
- 将 JSON 的值加载到 JavaScript