I'm facing a peculiar dilemma concerning variable scoping and accessing their values.
Here's a brief snippet of the component causing the issue:
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',
// Unsure if all these are necessary 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(); //Function call
});
//Alternative function call location
}
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())
);
}
}
This snippet depicts my component struggles. The challenge lies in accessing local variables within the InitTiles function.
When I place the function call at its current spot (as indicated by the comment The function to call
), everything runs smoothly.
However, when I shift that call outside of the
this.usersService.getUsers().then(...)
block (marked as Alternative call place
), I face difficulties reading the values of local components.
What could be causing this? Is it due to variable assignment within the scope of getUsers function or is there perhaps another underlying issue related to scopes?
If anyone can provide further insight on this matter, I would greatly appreciate it.