从angular 2中的对象访问特定值
我在angular 2项目中有一个函数从angular 2中的对象访问特定值,angular,object,angular2-services,angular2-directives,Angular,Object,Angular2 Services,Angular2 Directives,我在angular 2项目中有一个函数 this.fetchedData= this._visitService.getchartData().toPromise(); console.log("WORKING I HOPE0", this.fetchedData)` 它给出了输出: WORKING I HOPE0 ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)} __zone_sy
this.fetchedData= this._visitService.getchartData().toPromise();
console.log("WORKING I HOPE0", this.fetchedData)`
它给出了输出:
WORKING I HOPE0
ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)}
__zone_symbol__state:true
__zone_symbol__value:Array(2)
0:{date: "2018, 03, 14", value: 11}
1:{date: "2018, 03, 15", value: 1}
length:2
__proto__:Array(0)
__proto__:Object`
是否可以访问
\uuuu zone\u symbol\uuu value
以将其作为一个对象获取整体,甚至仅从中检索数据。我尝试使用console.log(“WORKING I HOPE0”,this.fetchedData.\uu区域\u符号\uu值)
,但似乎不起作用。我不是在寻找任何替代方法。因此,如果我想知道这是否可能,为什么不可能。我想你应该这样做:
this._visitService.getchartData().toPromise().then(data => {
this.fetchedData = data;
console.log(data);
})
对于您根据评论提出的查询,请尝试以下操作:
this._visitService.getchartData().toPromise().then(data => {
this.fetchedData = data;
console.log(data);
this.processFetchedData(); // call the function once this.fetchedData is initialized
})
processFetchedData(){
console.log(this.fetchedData); // check the console
}
既然您想知道“为什么”方面:- 你必须先等待承诺的解决。在解析函数的成功处理程序中,您将获得数据。现在,“fetchedData”变量存储promise,它将只具有promise特定的功能,而“不”实际数据。 解析后,如下所示,您可以检索数据并执行所需的解析 实际有效的代码是上面@Vivek Doshi使用“then”函数给出的代码 您可以按如下方式添加特定的成功/失败处理程序(如果您希望单独添加):-
先初始化对象,然后再将对象分配给它们
this._visitService.getchartData().toPromise().then(data => {
this.fetchedData = {}; //initialize object
this.fetchedData = data;
console.log(data);
})
承诺在异步操作完成或失败时处理单个事件
- 它返回一个值
- 不能取消
- 它提供了一个带有try/catch和async/await的可读代码
this._visitService.getchartData().toPromise()
.then(response => {
this.fetchedData = response;
console.log(response);
})
.catch(error => { console.log(error) });
如果您的响应来自http调用:
this._visitService.getchartData().toPromise()
.then(response => {
var json = response.json();
this.fetchedData = json;
console.log(json);
})
.catch(error => { console.log(error) });
我试过了,我知道它是有效的,但在那之后,
this.fetchData
只在特定函数中可用,但我希望能够在另一个函数中访问它。不,当您将它分配给this.fetchData,{fetchData | json}时,它也在函数之外可用
将这一行放在模板侧,你就会明白,它只有在初始化时才可用,我不想要模板中的数据,我想要它在代码中。@AtulStha,你可以从那时起调用第二个函数,这样第二个函数将被调用一次this.fetchedData
被初始化
this._visitService.getchartData().toPromise()
.then(response => {
var json = response.json();
this.fetchedData = json;
console.log(json);
})
.catch(error => { console.log(error) });