【发布时间】:2017-03-24 15:20:49
【问题描述】:
我正在学习 Angular2 从 $http GET 请求中获取数据。目前,数据不显示。我认为这是因为我的服务在我的组件渲染后传递了数据。我做了一些搜索,但仍然没有得到它。我在代码中添加了两个console.log(data),这是我的控制台截图。
这是我在 arr-detail.component.ts 中的ngOnInit():
import { TbArr } from './../../shared/models/tb_arr';
private data: TbArr;
ngOnInit() {
//method 1
this.route.params
.switchMap((params: Params) => this._dbService.get('MyAPI.php', 'id=' + params['id']))
.subscribe((d:TbArr) => this.data = d)
console.log(this.data);
/**method 2
* this.id = this.route.snapshot.params['id'];
* this._dbService.get('MyAPI.php', 'id=' + this.id)
* .subscribe(d => {
* this.data = d;
* });
**/
/**method 3
* this.route.params.subscribe(params => {
* if (params['id']) { //got the id from url
* this._dbService.get('MyAPI.php', 'id=' + params['id'])
* .subscribe(d => {
* this.data = d;
* });
* }
* });
**/
}
这是我在 db.service.ts 中的 GET 函数:
get(api: string, options: any) {
return this.dbRequest('get', api, options);
}
dbRequest(method: string, api: string, options: string) {
let observable: any;
const backendUrl_json = 'http://XXX.XX.XX.XX/api/json/';
observable = this.http[method](backendUrl_json + api, {search: options});
observable = observable.map(res => res.json());
console.log(method, backendUrl_update + api, options);
observable.subscribe(
d => { console.log(d); },
e => { console.log(e); }
);
return observable;
}
这是我的组件 html 文件:
<table *ngIf="data">
<tbody>
<tr>
<td>ID:</td>
<td>{{data?.id | async}}</td>
</tr>
<tr>
<td>Date:</td>
<td>{{data?.date | async}}</td>
</tr>
</tbody>
</table>
这是我的 tb_arr,它有 TbArr 接口:
export interface TbArr {
id:number;
date:any;
}
更新我的问题:
表格显示在网页上,但没有显示数据。
当我在控制台中打开“对象”时,我得到了这个:
有人对此有任何想法吗?非常感谢你。如果您需要更多信息,请给我留言。
【问题讨论】:
-
您能否添加您的 json 的样子...或者更准确地说,当您 console.log 时数据的样子?
-
@AJT_82 我添加了控制台截图。
标签: angular angular2-routing angular2-services