2016-08-17 97 views
1

我有一个奇怪的问题,关于变量范围和访问这些变量的值。Angular2范围问题

我基本上这样(短样品)成分:

import { Component } from '@angular/core'; 
import { HTTP_PROVIDERS } from '@angular/http'; 
import { InputText, DataTable, Button, Dialog, Column, Header, Footer, Panel, ProgressBar, Dropdown, SelectItem, 
SplitButton, SplitButtonItem, Toolbar, SelectButton, OverlayPanel, Checkbox, 
ToggleButton } from 'primeng/primeng'; 
import { User } from './../users.models'; 
import { UsersService } from './../users.service'; 
import { Router, ActivatedRoute }  from '@angular/router'; 
import { BbTile } from "./../../../shared/tile/tile.component"; 
import { BbTileModel } from "./../../../shared/tile/tile.model"; 

@Component({ 
    templateUrl: 'app/pages/users/dashboard/index.html', 
    selector: 'brandbassador-app', 
    // Honestly I'm not sure if all of these are required here 
    directives: [(...), BbTile], 
    providers: [HTTP_PROVIDERS, UsersService] 
}) 

export class UsersDashboardComponent { 
    // Data variables 
    tiles: BbTileModel[] = []; 
    // Statistics variables 
    totalRevenue: number; 
    usersCount: number; 
    averageEngagementRate: number; 
    totalReach: number; 

    ngOnInit() { 
     console.log("INIT "); 

     this.usersService.getUsers().then(
      users => { 
       this.users = users; 
       this.usersCount = this.users.length; 
       this.getTotalRevenue(); 
       this.getAverageEngagementRate(); 
       this.getTotalReach(); 
       this.getMostActive(); 
       this.getTopPerformers(); 

       this.initTiles(); //The function to call 
      }); 

     //Alternative call place 
    } 

    initTiles() { 
     this.tiles.push(
      new BbTileModel("USERS", (this.usersCount).toString()), 
      new BbTileModel("REVENUE", (this.totalRevenue).toString()), 
      new BbTileModel("AVERAGE ENGAGMENT RATE", (this.averageEngagementRate).toString()), 
      new BbTileModel("REACH", (this.totalReach).toString()) 
     ); 
    } 
} 

所以,这只是我的组件的片段。我无法从我的InitTiles函数中访问局部变量。

基本上,只要我在当前位置(一个注释为The function to call)上有我的函数调用,一切正常。

但是,如果我将该呼叫移动到this.usersService.getUsers().then(...)之外(一个注释为Alternative call place),我将失去从本地组件读取值的所有能力。

这是怎么发生的?是因为变量是在函数的范围内分配的,还是在后台有关于范围的其他问题?

任何人都可以详细说明这个吗?

回答

2

当执行

//Alternative call place 

,调用getUsers().then(...)还不发生。

这是异步执行的正常行为。
您传递给then(...)的代码在异步呼叫的响应到达时执行。 then(...)之后的代码立即执行。

+0

好的,所以我的错误是,我期待数据在那里还没有实际存在。我认为这将是一些喜欢的东西。所以我可以在'then(...)'之后说'我可以添加另一个'then()'来调用/初始化TileModel? –

+0

你可以这样做,但是当你可以将代码移动到你已有的'then(...)'中时,添加另一个'then(...)'有什么意义呢? –

+1

除了强迫症之外没有别的原因:D –