Dealing with Problems in Angular 2 Scopes

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.

Answer №1

Once the

//Alternative call place

statement is triggered, the getUsers().then(...) method has not yet been invoked.

This asynchronous behavior is standard practice.
The code you provide to then(...) will run once the async response is received. Any code following then(...) will execute immediately.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with unit testing a ViewportRuler in Angular 2 Material Library

I am currently working on an Angular2 component that includes a tab control from @angular/material. During testing of my component (refer to the simplified code below), I encountered the following error: Error: Error in ./MdTabHeader class MdTabHeader - ...

Tips on sending data to an Angular ng-bootstrap modal for data binding

Scenario: ChildComponent - with numerous ngModel binding elements. <input [(ngModel)]="TryToPassDataModel.name">; ParentComponent - btn.onClick = function() { this.bsModalRef = this.modalService.open(ChildComponent, TryToPassData ...

issues arise when deploying the Angular application on GitHub pages

Encountered an error while attempting to deploy my Angular application on GitHub pages using angular-cli-ghpages https://i.sstatic.net/ATIbR.png The bash commands I used when pushing the website to GitHub were as follows: ng build --prod --base-href ...

Identifying Similar Components in Angular 4: A Guide to Recognizing Rendered Elements

I am working with a clock.component.ts file and a dashboard where I need to display the clock multiple times based on the number of assigned runners for each user. For example, if a user has 3 assigned runners, I need to render the clock component 3 times. ...

Using a forEach loop within an Else statement is ineffective

I've encountered an issue while trying to merge two arrays and create a new one. It seems that my forEach loop inside the else statement is returning undefined. I'm unsure if I made a mistake in my approach or if forEach is not meant to be used w ...

Using Angular2's *ngIf directive to conditionally display content based on the length of

After referring to https://angular.io/docs/ts/latest/guide/displaying-data.html and a stack post on how to check for an empty object in an angular 2 template using *ngIf, I am still encountering a syntax error stating "self context undefined". If I remove ...

Tips for adding temporary text in filter input of Kendo UI Grid using Angular

I'm currently working with Kendo UI Grid in conjunction with Angular, and I am struggling to find a solution for adding text or a placeholder in filter inputs using Typescript. Within my code, I am utilizing the kendoGridFilterCellTemplate: <kend ...

Guide to emphasizing important terms in an Angular Material table

I am currently implementing Angular Material and I have a dynamically searched keyword. I need to highlight this keyword in the table, but my previous attempt using innerHTML did not work as expected. View Demo HTML: <h2>Searched word: UM</h2> ...

Tips on adding an external type to a global .d.ts file

In my TypeScript project, I am utilizing Moment.js for dealing with datetime objects. As part of this, I wish to create an object type that includes a key holding a value of type Moment. However, upon adding the following snippet to a global definition fi ...

Ways to update the UI dynamically in Angular without the need to refresh the entire page

On my page, I have multiple charts and I'm facing an issue where the chart UI does not update immediately when I try to make a delete call by clicking the delete button. I always have to refresh the browser to see the changes. I have provided the ful ...

The combination of Observable streams in combineLatest will persist even if one encounters a

I have a function designed to retrieve multiple documents from Firebase. fetchDocuments(documentIds: string[]): Observable<TreeNodeDocument[]> { const observables = []; for(let id of documentIds){ observables.push(this.fetchDocument( ...

Creating an Ionic 2 hybrid mobile app with a navigation controller: Step-by-step guide

While Angular 2 has been officially released, Ionic 2 is still in beta. I'm on the lookout for some great examples of Ionic 2 Hybrid Mobile Apps with a Navigation Controller. I stumbled upon this helpful tutorial at Icoderslab. Are there any other res ...

Ensure that a string contains only one instance of a specific substring

I need a function that removes all instances of a specific substring from a string, except for the first one. For example: function keepFirst(str, substr) { ... } keepFirst("This $ is some text $.", "$"); The expected result should be: This $ is some tex ...

Oops! Looks like we've encountered a bit of a snag: HttpClient provider is missing

I am currently facing an issue with my code in Testing.ts file. Below is the code segment from Testing.ts: let injector = ReflectiveInjector.resolveAndCreate([ TestService ]) var myInstance = new myTest(injector.get(TestService)); The TestService.ts ...

Fade In Effect in Angular 2 Using SwitchCase

Hi everyone, I'm facing an issue with making my switch cases fade in after one is called. Here's what I have so far. When the correct switch case is entered in the input field, I want the current one to fade out and the new one to fade in. How ...

Tips on how to remove a function from a union

type A = (() => void) | (() => number) | string type B = Another<A> // string Is there a way to remove all functions from type A? This would result in type B being string ...

The Cypress tests run successfully on a local machine, but encounter issues when running on Gitlab CI

My current setup involves utilizing Cypress to test my Angular application. Interestingly, everything runs smoothly when I execute the tests locally. However, the scenario changes once I run the tests in Gitlab CI as it ends up failing. Looking at my pack ...

Data service with a variety of return types

I have developed a versatile data service structure that has the following implementation: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Observable& ...

Ionic2: Access your account via an External Source

Challenges have arisen in implementing the authentication process for our app according to the client's requirements. I am seeking guidance on how to set up the app so that users are redirected to an external webpage upon opening, where they can comp ...

Issue with Ionic Webview not properly synchronizing cookies upon initial launch on IOS devices

I am seeking assistance with an issue in my Ionic 5 app built with Angular and Cordova. While testing on browsers and Android devices, everything works perfectly. However, once the app is installed on my iPhone through Xcode, the cookies are not being sent ...