What is preventing me from manipulating this Object outside of the ngOnInit() function?

I've been working on a project that involves fetching data from the server and manipulating it within the .ts file. However, I seem to be facing a common issue related to Typescript/angular concepts that I'm struggling to grasp...I would really appreciate some assistance with this

user: any;

public doStuff(){
    alert(this.user.username);
 }

The user object contains various properties, such as 'username', which is initialized in the ngOnInit() block. I am setting it in the ngOnInit method. The service injection is done correctly and the following code works perfectly fine

ngOnInit() {

this.authService.getProfile().subscribe(profile =>{
    this.user= profile.user;
    this.initStuff();

  },
  err => {
    console.log(err);
    return false;
  });
 }

When I try to call the doStuff() method outside of that code block, it stops functioning and the browser-console shows an error message "cannot read property 'value' of undefined" - why is it showing undefined? Interestingly, when I use {{user.username}} in the component.html, it displays the correct username

ngOnInit() {

this.authService.getProfile().subscribe(profile =>{
    this.user= profile.user;
  },
  err => {
    console.log(err);
    return false;
  });
    this.initStuff(); // why can't I call it here? This is where I typically call all my other doStuff() methods
 }

Answer №1

The reason it is not functioning properly is due to the fact that getProfile() is an asynchronous operation. If you are looking to manipulate server data, it must be done within the subscribe next() method. This method is triggered when the async operation returns a new value.

If you trigger initStuff() outside of the next() method, it will run immediately, leading to the error "cannot read property 'value' of undefined".

I hope this explanation proves helpful to you.

Answer №2

From my understanding, it seems that you are attempting to access data that has not been received yet, which is causing the error in your console. In the function being described, an Observable (RxJs) is being used and it is asynchronous. If you intend to perform operations on the 'profile' variable, you should place them within the callback of the Observable, typically inside the subscribe method.

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

"Sorry, but the mean stack module seems to be missing

I recently started coding in MEAN Stack and I'm following a guidebook titled Mean Web Development by Amos Q. Haviv. However, I encountered an issue with the code below: var express = require('express'); module.exports = function() { c ...

Express, the mongoose package delivers a response of an empty array

I have encountered a common issue regarding pluralization with mongoose default model names. Despite trying various solutions, the problem persists as I am getting an empty array as the result. In my local mongoDB database, there are 2 documents in the "us ...

React app's compilation is failing due to non-compliant ES5 code generation of the abab module, resulting in errors on IE

Can anyone explain why a create-react-app project using TypeScript and configured to generate ES5 code is not functioning on IE11 due to the "atob" function from the 'abab' package not being compiled into ES5 compliant code? module.exports = { ...

The 'validate' property within the 'MappingService' class cannot be assigned to the 'validate' property in the base class 'IMappingService' in typescript version 2.8.0

Currently, I am utilizing the AngularJS framework (version 1.5.8) in tandem with the latest TypeScript files (2.8.0). However, upon updating to the newest version of TypeScript, the code below is failing to compile. The IMappingService interface: export ...

Utilizing unique symbols to dynamically add form elements to an HTML page with jQuery's append method

I am facing an issue with creating forms on my HTML page. Here is an example of how I am trying to do it: <form action="/tasks/<%= allTasks.e[0].id %>/delete" method="POST"> <button class="deleteTask">Delete</button> </f ...

Tips for utilizing regex to locate words and spaces within a text?

I'm feeling so frustrated and lost right now. Any help you can offer would be greatly appreciated. I am currently dealing with an issue in Katex and Guppy keyboard. My goal is to create a regex that will identify the word matrix, locate the slash that ...

What is the best way to initiate an event using the onMousewheel function?

I am currently working on a WebGL application where I have a sphere object that utilizes orbit controls for zooming in and out. My goal is to set up an event for the mousewheel so that when I zoom on the WebGL block, the corresponding map location also zo ...

Determining the quantity of displays

Can we detect the number of screens in use using JavaScript or jQuery? We are working on an application that should not be displayed on multiple screens, even if the hardware allows for it. Appreciate any assistance with this matter. Thank you. ...

Encounter a 404 error message coming from nginx while running ng build

Hello, I'm new to angular and attempting to run my angular application within a docker container. After executing ng build or ng build -prod and setting it up to run in a docker using the following dockerfile: ### STAGE 1: Build ### FROM node:12.7-a ...

Guide on displaying a partial template upon clicking a specific menu item using Meteor JS

I am a newcomer to Meteor JS and I am looking for a way to render a specific template to a specific part of my web app when a menu is clicked. I am currently using iron-router and layout template. The current layout is functioning correctly. For example, w ...

A step-by-step guide on creating a user-specific signature in Node.js

Is there a way to incorporate user-generated signatures similar to how Amazon delivery personnel have recipients sign on their mobile devices using NodeJS? Any helpful resources would be greatly appreciated. I am working with Angular for the frontend and ...

Converting JSON to a HashTable using Java Jackson Serialization

Trying to serialize a list of JSON blobs and extract specific keys to create a HashTable during serialization. Here's an example of the JSON: [ { "name": "sally", "id": 1, "eye_color": "green" }, { "name": ...

What is the best way to transform a standard array into a record without losing the specific data types in each position?

Imagine type Individual = { name: string; age: number; }; const john = { name: "John", age: 28, } as const; const emily = { name: "Emily", age: 35, } as const; I am looking to create a function that takes an individual an ...

Leveraging replaceWith() alongside animate or scroll methods can enhance the user

Can we switch one div with another div while incorporating an animation effect, such that the old div slides to the left while the new one slides in from the right side of the page? My goal is to have both divs present on the page simultaneously while the ...

Learn the best way to efficiently transfer multiple checkbox selections in a single object using AJAX

In my form, I have 4 checkboxes with unique IDs like filter_AFFILIATION_1, filter_AFFILIATION_2, and so on up to 4. My goal is to dynamically send the values of checked checkboxes to the server using an ajax call. Below is the snippet of my code: $(&a ...

I am facing an issue where I am unable to execute 'npm run server' after compiling an Angular app using 'npm run

I encountered an issue with my Angular app that is utilizing Angular Universal. After bundling the app using npm run build:prod, everything seemed to be fine without any errors. However, when I attempted to view the app in the browser by running npm run se ...

Steps to implement provided information in a post within the header of a webpage

Recently, I started creating websites from scratch and I encountered a problem that I could use some help with. The issue is when I have a YouTube video embedded in a post, but I want to showcase the video in the header section of that specific post URL wi ...

Obtaining the name of the image that has been uploaded using jQuery

//Image upload function $(function() { $(":file").change(function() { if (this.files && this.files[0]) { var reader = new FileReader(); reader.onload = imageIsLoaded; reader.readAsDataURL(this.files[0]); } }); }); function im ...

In C#, how can the HTMLAgilityPack be utilized to extract a value from within a script tag?

I'm currently working with HTMLAgilityPack and I need to extract a value from a script tag. Here is the code: <div id="frmSeller" method="post" name="frmSeller"> <div class="clear"></div> <script type="text/javascript" language=" ...

Creating a dynamic search bar with multiple input fields in HTML

My JSON input for typeahead looks like this: [{"q": "#django", "count": 3}, {"q": "#hashtag", "count": 3}, {"q": "#hashtags", "count": 0}, {"q": "#google", "count": 1}] This is the code I have to implement typeahead functionality: var hashTags = new Blo ...