[英]How to get HTTP JSON-response into HTML (Ionic2, Angular2, TypeScript, PHP, JSON)?
[英]Ionic2 angular2 http get json from external api
我知道这可能是一个菜鸟问题,因为我已经看过更复杂的内容,但是要了解复杂的内容,我需要先了解简单的内容。
我试图从api(laravel)的JSON字符串中获取名称:
{"name":"Abigail","state":"CA"}
使用返回此代码的路由创建代码(在laravel中):
return response()->json([
'name' => 'Abigail',
'state' => 'CA'
]);
在ionic中,我得到了以下文件:
page.ts:
export class Page {
constructor(public http: Http) {}
getJson() {
this.http.get('http://external.ip/api')
.map(res => res.json())
.subscribe(
data => this.data = data
);
}
}
page.html中:
<ion-header>
<ion-navbar>
<ion-title>App</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-content>
<ion-list>
<ion-item>
<h3>{{data.name}}<h3>
</ion-item>
</ion-list>
</ion-content>
</ion-content>
我知道这行不通,但是我需要帮助才能使它工作。 我希望以后可以添加更多名称。 之后,我希望能够将数据发布到api(例如添加名称或更改日期)。
假设运行了getJson(),这应该可以工作(我添加了OnInit代码来做到这一点)。 还提供了一个简单的简单请求帖子示例。 您可以订阅该帖子,也可以保留原样。
//Will need on OnInit to run getJson()
import {Component, OnInit} from '@angular/core';
export class Page implements OnInit {
constructor(public http: Http) {}
data: any;
getJson() {
this.http.get('http://external.ip/api')
.map(res => res.json())
.subscribe(
data => this.data = data;
);
}
//run getJson() at initial load
ngOnInit() {
this.getJson();
}
postJson(data:any) {
let headers = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: headers });
return this.http.post('http://52.11.14.57:4000/api/events', JSON.stringify(data), options)
.map((res: Response) => res.json());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.