Javascript Angular 2 HTTP显示特定于JSON的值
我有一段代码可以读取一些json数据:Javascript Angular 2 HTTP显示特定于JSON的值,javascript,angular,Javascript,Angular,我有一段代码可以读取一些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)="makeRequ
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"
}
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),
);
从'angular2/core'导入{Component};
从'angular2/Http'导入{Http,Response};
@组成部分({
选择器:“我的应用程序”,
模板:`
基本要求
请求
加载。。。
{{data}json}
`
})
导出类AppComponent{
资料:对象;
加载:布尔;
构造函数(公共http:http){
}
makeRequest():void{
这是。加载=真;
this.http.request('http://jsonplaceholder.typicode.com/photos/1')
.订阅((回复)=>{
this.data=res.json();
这一点:加载=错误;
}); }
}
这是返回的json:
{
“albumId”:1,
“id”:1,
“标题”为“脸上的肉和脸上的肉”,
“url”:”http://placehold.it/600/92c952",
“缩略图URL”:http://placehold.it/150/30ac17"
}
{{data | json}}
正在返回所有数据
我只想拿这个头衔为例。
所以我试了一下:
{{data.title | json}
但这不起作用
仅显示标题的正确方式是什么?数据是一个JSON对象,因此如果使用数据,则使用|JSON管道。 如果要使用非对象的值,则直接使用该值即可
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;
});
添加地图并切换以获取
<pre>{{data?.title}}</pre>
然后在模板中像这样使用它{{data.title}
这里还有几个http示例:像这样使用elvis操作符
{{data?.title}
Elvis运算符(?)表示数据字段是可选的,如果未定义,则应忽略表达式的其余部分。您可以尝试此操作
现在可以执行{{myData.title}
对于多个对象,请使用:ngFor
{{item.title}
这不会返回任何内容……编辑说:未解决的变量title也有同样的问题。只需在html代码中写入对象,即可在视图中打印“[object object]”。尝试获取任何属性会导致“EXCEPTION:TypeError:l_fav0在[null]中未定义”,其中“fav”是我的对象的名称。我不知道我遗漏了什么,但这和Satch3000的问题是一样的。整个网络只是给出了同样的建议,没有任何帮助,也找不到任何例子,除了过于简单的例子。以下是数据:{“albumId”:1,“id”:1,“title”:“accusamus beatae ad facilis and similique qui sunt”,“url:”,“thumbnailUrl:”}需要一张地图和一个get电话
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),
);
<li *ngFor="let item of myData">
{{item.title}}
</li>