Zed_Blade Zed_Blade - 3 months ago 17
TypeScript Question

Angular2 scope Issues

I'm having a weird issue regarding variables scoping and accessing the values in those variables.

I basically have this (short-sample) component:

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


So, this is just a snippet of my component. And I'm having trouble accessing the local variables from within my InitTiles function.

Basically, whenever I have my function call on the current location (the one commented as
The function to call
) everything works ok.

However, if I move that call to outside of the
this.usersService.getUsers().then(...)
(The one commented as
Alternative call place
) I lose all ability of reading the values from the local component.

Why is this happening? Is it because the variables are being assigned inside the scope of the
getUsers
function or is there some other issue going on in the background regarding scopes?

Can anyone elaborate on this please?

Answer

When

//Alternative call place

is executed, the call to getUsers().then(...) didn't happen yet.

This is normal behavior of async execution.
The code you pass to then(...) is executed when the response from the async call arrives. The code after then(...) is executed immediately.

Comments