从 angular 中的对象访问特定值 2

accessing specific values from Objects in angular 2

我在我的 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_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`

是否可以访问 __zone_symbol__value 以将其作为一个对象完整获取,甚至只是从中检索数据。我尝试使用 console.log("WORKING I HOPE0", this.fetchedData.__zone_symbol__value) 但它似乎不起作用。我不是在寻找任何替代方法。所以如果我想知道它是否可能以及为什么或为什么不。

我认为你应该这样做:

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
}

既然你想知道'why'方面:- 您必须先等待承诺解决。在解析函数的成功处理程序中,您将获得数据。现在,"fetchedData" 变量存储了承诺,它将只有承诺特定的功能和 "NOT" 实际数据。 解析后,如下所示,您可以检索数据并进行所需的解析。

实际有效的代码是上面@Vivek Doshi 使用 'then' 函数给出的代码。

您可以按如下方式添加特定的 success/failure 处理程序(如果您需要单独添加):-

var promise = serviceCall.toPromise();
promise.success( (data) => this.fetchedData = data );
promise.error( (err) => console.log(err.message) );

在将对象分配给他们之前先初始化您的对象。

this._visitService.getchartData().toPromise().then(data => {
    this.fetchedData = {}; //initialize object
    this.fetchedData = data;
    console.log(data);
})

A Promise 在异步操作完成或失败时处理单个事件。

  • 它 returns 一个值。
  • 不可取消。
  • 它提供了具有 try/catch 和 async/await 的可读代码。

你应该等待 promise 解决,所以这是你需要的:

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) });

我在重构代码以使用 async/await 时遇到了同样的问题,但在这种情况下忘记在函数调用前加上 await。

加入例如

async MyFunction() {

    this.fetchedData = await this._visitService.getchartData().toPromise();

}

如果这是您的意图(在我的情况下是这样),可能会奏效。