我有一项从后端检索数据的服务。我可以使用此代码.do(data =>console.log('All: ' + JSON.stringify(data)))
--->在浏览器控制台中查看检索到的数据以JSON格式显示我的任何数据数组。
在我的组件中,我订阅了该服务,但我无法弄清楚如何访问检索数据来操作它,因为我需要作为参数传递给函数。
组件:
import { Component, OnInit } from '@angular/core';
//inject services
import { HitoService } from '../hito.service';
import {IHito} from '../form-hito/interfaceHito';
declare var vis: any;
declare var swal: any;
declare var $: any;
@Component({
selector: 'app-time-line',
templateUrl: './time-line.component.html',
styleUrls: ['./time-line.component.css'],
providers: [HitoService]
})
export class TimeLineComponent implements OnInit {
hito1: IHito[];
constructor(private _hitoService: HitoService) { }
ngOnInit() {
this._hitoService.getHitos()
.subscribe(hito1 => this.hito1 = hito1);
console.log("hitos de DB:");
console.log(this.hito);
this.drawtimeline1_1();
}
我在控制台中看到的数据是:
All: [{"_id":"587817c60de1f905b5811786","descrip":" testeo de creacion de hito ","endDate":"2017-01-26","startDate":"2017-01-08","nameHito":"hito test","__v":0},{"_id":"5878180a0de1f905b5811787","descrip":" testeo de creacion de hito otra vez ","endDate":"2017-01-15","startDate":"2017-01-06","nameHito":"hito test number 2","__v":0},{"_id":"587820820b0a4e05c5678ab7","descrip":" testeo de creacion de hito una vez más ","endDate":"2017-01-15","startDate":"2017-01-06","nameHito":"hito test number 3","__v":0},{"_id":"5878d262639a4d0323bfcd4b","descrip":"lslskkdldjdjh","endDate":"2017-01-01","startDate":"2017-01-01","nameHito":"kkakkakakakkaa","__v":0}]
如何在订阅后访问每个backend_data.descrip?
答案 0 :(得分:2)
你必须添加大括号:
ngOnInit() {
this._hitoService.getHitos()
.subscribe(hito1 => {
this.hito1 = hito1
console.log("hitos de DB:"...); // defined!
});
console.log("hitos de DB:"...); // undefined!
}
第二个console.log在实际收到数据之前执行,这就是为什么你实际上可能没有获得数据的原因。
如果您尝试在视图中显示数据,则可能需要使用ngIf
或elvis运算符才能呈现数据。这是因为调用是异步的。
所以例如用
包装你的html<div *ngIf="hito1">
<!-- Your data manipulation here -->
</div>
编辑:如果你想访问你的属性,它很容易完成。以你的json为例,看起来像这样:
[
{
"_id": "587817c60de1f905b5811786",
"descrip": " testeo de creacion de hito ",
"endDate": "2017-01-26",
"startDate": "2017-01-08",
"nameHito": "hito test", "__v": 0
},
......
]
可以迭代和显示整个数组和属性,例如显示id和name。下面用* ngFor迭代整个数组,并显示每个对象的id和描述。
<div *ngIf="hito1">
<div *ngFor="let data of hito1">
<div>{{data._id}}</div>
<div>{{data._descrip}}</div>
</div>
</div>
答案 1 :(得分:2)
您应该对代码进行一些更改
ngOnInit() {
this._hitoService.getHitos()
.subscribe(hito1 => {
this.hito1 = hito1
console.log(this.hito);<-- if you console you will get output
this.drawtimeline1_1();<-- you can pass this.hito as parameter if you want
});
}
用于访问每个的描述,你可以这样做
1)如果你想在html视图中显示
<ul *ngIf="hito1">
<li *ngFor="let values of hito1">{{values.descrip}}</li>
</ul>
2)如果你想在组件区域访问,你可以使用lodash https://lodash.com/docs/4.17.4#forEach