2016-05-30 44 views
-1

我想通过角2变量来影响一个JSON属性的值,我试图访问它在我的应用程序组件是这样的:影响JSON属性中的变量angular2

export class AppComponent{ 

    count : any; 

    constructor(private _getService : GetService) { 

     this._getService.getPosts(this.urlG) 
      .subscribe(
       result => this.actionsG = result, 
       error=> console.error('Error: ' + error), 
       ()=> console.log('finish! ActionsG') 
      ); // getting the JSON FILE 

     this.aCount = this.actionsG.actionList[0].count; 

     // that's what i'm trying to do to get the values of count in the json 
     // file and stock it into aCount.. 
    } 
} 

我的JSON文件:

{ 
    "actionList": { 
     "count": 70, // 
     "list": [ 
      { 
       "Person": { 
        "name": "David", 
        "age": "30", 
        "id": "D5UG8R", 
        ... 

回答

1
this.aCount = this.actionsG.actionList[0].count; 

result => this.actionsG = result 
之前执行

做,而不是

this._getService.getPosts(this.urlG).subscribe(result => { 
    this.actionsG = result; 
    this.aCount = this.actionsG.actionList[0].count; 
}, error=> console.error('Error: ' + error),()=> console.log('finish! ActionsG')); 
+0

当我做到了,通过打印aCount的值:'的console.log( “帐户:” + this.aCount); '我得到值undefined它意味着我无法通过访问json文件中的值:this.actionsG.actionList [0] .count;当我在html中打印时,我可以通过{{actionList?.count}}访问它。我不知道如何去获取变量的值 – melina

+0

你需要在'subscribe(...) )',因为这个代码在服务器响应到达时执行。如果你在'subscribe()'之后有你的代码,它会在响应到达之前执行,因此不确定。 –