Zed_Blade Zed_Blade - 1 year ago 167
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";

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

users => {
this.users = users;
this.usersCount = this.users.length;

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

//Alternative call place

initTiles() {
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
(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
function or is there some other issue going on in the background regarding scopes?

Can anyone elaborate on this please?

Answer Source


//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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download