The unavailability of passed-in values during the runtime of a function within an Angular application

It's becoming clear to me that there is a piece of the puzzle missing when it comes to understanding exactly when certain function outputs are available in JavaScript.

In my Angular application, I am trying to extract a user's initials by extracting the first letters of their first and last names from API data using two separate functions. These functions are functioning properly, displaying the correct results in the console:

getFirstNameFirstLetter() {
    if (this.authenticationService.isAuthenticated()) {
        const userObj = JSON.parse(sessionStorage.getItem('currentUser'));
        const userInfo = userObj.data;
        const firstName = userInfo.name.first;
        const firstNameFirstLetter = firstName.trim().charAt(0);
        console.log(firstNameFirstLetter);
        return firstNameFirstLetter;
    }
}

getLastNameFirstLetter() {
    if (this.authenticationService.isAuthenticated()) {
        const userObj = JSON.parse(sessionStorage.getItem('currentUser'));
        const userInfo = userObj.data;
        const lastName = userInfo.name.last;
        const lastNameFirstLetter = lastName.trim().charAt(0);
        console.log(lastNameFirstLetter);
        return lastNameFirstLetter;
    }
}

However, where I'm encountering confusion is when attempting to use the values returned by these functions to generate the user's initials:

getInitials(firstNameFirstLetter, lastNameFirstLetter) {
    if (this.authenticationService.isAuthenticated()) {
        if (!this.firstNameFirstLetter || !this.lastNameFirstLetter) {
            console.log('Names not ready!');
            return;
        } else if (this.firstNameFirstLetter && this.lastNameFirstLetter) {
            console.log(firstNameFirstLetter + lastNameFirstLetter);
            return firstNameFirstLetter + lastNameFirstLetter;
        }
    }
}

Every time I try to pass the outputs of the previous functions into getInitials(), "Names not ready!" gets printed to the console.

For context, I am invoking these functions within Angular's ngOnInit lifecycle hook as follows:

ngOnInit() {
    this.getFirstNameFirstLetter();
    this.getLastNameFirstLetter();
    this.getInitials(this.firstNameFirstLetter, this.lastNameFirstLetter);
}

The crux of the issue lies in what values are accessible at what points, as evidenced by receiving 'undefined' values when debugging the inputs passed to getInitials(). This indicates that the function is being executed before the other two have completed, hence prompting 'Names not ready!' to be logged. The question then becomes, what fundamental architectural concept am I overlooking to address this dilemma?

Answer №1

What's happening here is that JavaScript isn't recognizing the return values for getFirstNameFirstLetter and getLastNameFirstLetter, causing it to move on to the next call without waiting for the previous ones to finish. This creates a race condition. To address this issue, you can modify your code as follows:

ngOnInit() {
    let temp1 = this.getFirstNameFirstLetter();
    let temp2 = this.getLastNameFirstLetter();
    this.getInitials(this.firstNameFirstLetter, this.lastNameFirstLetter);
}

By making this change, the functions will now wait for each other to complete before moving on to the next one.


In terms of scope, I don't frequently use const and there might be different rules to consider. Typically, variables set within a function are only accessible within that function. To access them outside the function, you should do something like:

this.firstNameFirstLetter = firstName.trim().charAt(0);

This allows you to utilize the variable beyond just the function itself.


To streamline your code further, you could simplify it by doing:

ngOnInit() {
    this.firstNameFirstLetter = this.getFirstNameFirstLetter();
    this.lastNameFirstLetter = this.getLastNameFirstLetter();
    this.getInitials(this.firstNameFirstLetter, this.lastNameFirstLetter);
}

or

ngOnInit() {
    let firstNameFirstLetter = this.getFirstNameFirstLetter();
    let lastNameFirstLetter = this.getLastNameFirstLetter();
    this.getInitials(firstNameFirstLetter, lastNameFirstLetter);
}

Choose the approach based on whether you need the variables again or just within that specific function context.

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

Utilizing Treant.js within a Vue.js application

After attempting to integrate the Treant.js library into my Vue app for creating a tree diagram from JSON data, I encountered some errors. In my main view, here are the import statements... import Vue from "vue" import store from "../../store" import { ge ...

Using AJAX in Rails to dynamically display information in a div on the webpage

In my project, I have a model named Area and what I want to achieve in the index page is loading the area_path(area) within a div element instead of redirecting users to another page. Here are the code snippets that I have implemented so far: <h3>W ...

Tips for integrating Excel files with NestJS

I'm in the process of developing a REST API that will utilize a third-party API to retrieve specific status information. The URLs needed for this API are stored in an Excel file, which is a requirement for this use case. My goal is to extract the URLs ...

The absence of a React JS button on the page

I'm in the process of creating a React demo application and I've come across this component: var MediaList = React.createClass({ displayName: 'MediaList', getInitialState: function() { return { tweets: getTweets(numTweets) ...

Tips for maintaining the reference of a Three.js object after importing it as an .obj file

If you want to learn how to incorporate a .obj file into your scene, the official documentation provides a helpful example that can be found here. const loader = new OBJLoader(); // Load the resource loader.load( // Resource URL 'models/monst ...

Experiencing password issues in Node.js

I am encountering an unusual issue with my nodejs module, specifically with connecting to MySQL. When I hardcode the password in the connection like this: client.password = 'password'; It connects successfully. However, if I try to pass the pa ...

Methods in JavaScriptInterface not identified (WebView on Android)

In my MainActivity, I have the following code: webView.addJavascriptInterface( new JavaScriptInterface( this ), "ajaxHandler" ); .... public class JavaScriptInterface { Context mContext; JavaScriptInterface( Context c ) { ...

Tips for replacing HTTP response in Angular 4

One of my challenges involves using a specialized HttpService that inherits from Angular's native Http: export class HttpService extends Http { } I am trying to figure out how to intercept/override the response: My attempt to do this looks like: r ...

Angular: extracting value from forkJoin nested within another observable's pipe

Here is the scenario that needs to be implemented: An API call is made which returns a response containing an array of objects. The objects are then mapped to another array of objects. For each item in this new array, another API call needs to be made. Th ...

The dependency graph of npm modules shows significant differences

I've been exploring the capabilities of the npm-remote-ls package to analyze dependency trees for modules. This tool is installed globally on my system. When I execute Command 1: npm-remote-ls object-assign The tree structure displayed is as follows ...

What is the best way to assign table rows to various interfaces in typescript?

Assuming I have the interfaces provided below: export interface IUserRow { id: string, state: string, email: string, } export interface ITableRow { id: string, [key: string]: any; } export type Rows = ITableRow | IUserRow; // additio ...

What is the best method for preserving HTML content using Ajax?

I am having difficulty storing HTML code in a database using AJAX. Despite having the correct connection information, I am unable to write to the table. <div id="others"> <div id="name"><input type="text" name="results" class="name"> ...

What is the best approach in AngularJS for implementing a browser modal that returns a promise?

How can I implement a custom modal in my code that allows me to perform an action only after the user clicks 'okay'? var modalInstance = this.$modal.open({ templateUrl: '/app/tests/partials/markTest.html', controller: ['$sc ...

Encountering Reference Error while Using AWS Amplify with Nuxt.js: Navigator Undefined

Currently, I am experimenting with Nuxt.js and AWS Amplify to leverage the benefits of SSR/SEO for my project. I have successfully integrated Amplify into my project and followed the "Manual Configuration" steps outlined in the Amplify Docs to set it up. ...

Having difficulties in TypeScript identifying types within a project containing multiple node_modules directories

I am currently in the process of transitioning a codebase from Flow to TypeScript. I am encountering an issue with the error message Cannot find module 'SOME DEPENDENCY' or its corresponding type declarations.ts(2307) for several dependencies tha ...

Updates to the AngularJS model are not appearing in the user interface

Despite executing the controller code, the values in the UI remain unchanged. The initial values are displayed without any issue. I've attempted to call $scope.$apply() at the end of each function (submit and transfer), but it didn't resolve the ...

Choosing to collapse a nested JSON arrangement in a targeted manner

Facing a challenging problem here and feeling clueless on how to tackle it. Any guidance or pointer in the right direction would be highly appreciated. My dataset looks like this: data = { "agg": { "agg1": [ { "keyWeWant": " ...

Notify when the focus is solely on the text box

How can I display an alert only when the focus is on a text box? Currently, I am getting an alert whenever I skip the text box or click anywhere on the page. The alert even appears when I open a new tab. Is there a way to fix this issue? Thank you for your ...

Encountering a 404 error when trying to reload the page?

My React Router is functioning properly in the development environment. Here's what I implemented in Webpack Dev Server: historyApiFallback: { index: 'index.html', } Now, when transitioning to production mode, I wanted to replicate the ...

The JavaScript alert message pops up two times consecutively

I encountered an issue while attempting to utilize a module named disclaimer in Drupal 7. The alert message "You must enter the year you were born in." appears twice and then redirects to a URL that should only be accessed after verifying that you are over ...