Assigning a value from an Angular Http subscription to a component variable is not allowed

Is there a way to retrieve data from an api and store it in a variable within an angular component? Specifically, I am attempting to assign the data received in the subscribe function to the loggedUser variable and then call a separate function within the subscribe block to navigate to another component using this object. However, I encountered an error: The requested path contains undefined segment at index 1. I also want to ensure that this object is accessible outside of the subscribe method as well. How can I achieve this?

 logIn() {
      this.portfolioAppService.logIn(this.loggingUser).subscribe((data) => {
      this.loggedUser = data;
      console.log(this.loggedUser);
      console.log(data);
      this.navigateToProfile(this.loggedUser.Id);
    });
  }

  navigateToProfile(id: number) {
    this.router.navigate(['/profile', id]);   
  }

View console output for more information

Answer №1

It appears that you have used the wrong property name when calling the function navigateToProfile.

Based on the information from your console output, it seems that the data object within the subscribe function is structured like this:

{
  id: 35,
  // ..
}

However, you are invoking the function in this way:

this.navigateToProfile(this.loggedUser.Id);

Instead, make sure to use the property id (in lowercase)

this.navigateToProfile(this.loggedUser.id);

In order to prevent similar issues in the future, consider being more specific and thorough in your testing. People tend to see what they expect to see and may mistakenly perceive a problem as more complex than it actually is. By attempting console.log(this.loggedUser.Id), you would have noticed the result of undefined, which would have helped you identify the issue on your own.

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

Unusual case of missing lines while reading a file using readline.createInterface()

const readline = require('readline') const fs = require('fs/promises'); (async function() { await fs.writeFile('/tmp/input.txt', [...Array(100000).keys()].join('\n')) await fs.writeFile('/tmp/other.tx ...

Looking to develop a dynamic JSON preview feature using AngularJS

Below is an example of JSON data: data: [{ test: { innertest: "2345", outertest: "abcd" }, trans: { sig: "sou", trip: [{ one: "2" }, { two: "3" }], otherac: "iii" },{ test: { innertest: "uuu", ...

What is preventing me from installing React and uninstalling create-react-app from my system?

I've exhausted all my options but still can't seem to figure out how to install ReactJS on my system. Every time I complete the installation process, I encounter this error message: A template was not provided. This is likely because you' ...

Refreshing an AJAX call automatically in Knockout JS

Greetings everyone! I'm currently working on setting up a simple setInterval function to automatically refresh my data every minute. The line that is giving me trouble is: setInterval(incidentViewModel.fetchdata,60000); I also attempted this: windo ...

Tips for fading out two elements after completing a drag and drop action

Visit this Codepen for more examples - Codepen I have been developing a drag and drop feature in my application. Once the item is dropped, it transitions from red to green and fades out smoothly. The droppable element behind the draggable should also fad ...

Library for visualizing JavaScript code using flowcharts and diagrams

Is there a jQuery-based javascript library available for client-side rendering and manipulation of flow-charts? I am open to other options as well. This question has been previously posed, but has not been revisited in a few years. Hopefully, there are ne ...

Can a new item be added to a list in React without affecting its sibling items?

Imagine I have the following setup: class Item extends React.Component { render() { console.log("Assume this action is time-consuming..."); return <li>{this.props.text}</li>; } } class List extends React.Component { constructor ...

Creating default values for MongoDB databases using bdhash in Express.js and mongoose asynchronously

What is the best way to set a default value (like bdhash which is async) for a field in my mongoose schema? Currently, I am only seeing a promise inside. I'm using async/await correctly, but why does it seem like I'm getting just a promise? I als ...

Executing a function within ng-repeat loop four times in AngularJs

In the code snippet below, a ul is populated with 21 phones using HTML: <li ng-repeat="phone in phones" ng-class="{'digestTest': countDigestOccurences(phone) }"> <p>{{phone.snippet}}</p> </li> The JavaScript method cou ...

Tips for manipulating specific URL redirection to an alternative URL within a NuxtJs application

Take this scenario, where the inputted URL is: http://localhost:3000/course-details The desired outcome should be a redirection to http://localhost:3000/courses I recall there being a method for achieving this, but it slips my mind at the moment. ...

Top method for dynamically generating a recursive treeview from data fetched from an API

I am currently learning Angular 2 and working on creating an expandable tree-view that pulls data from a potentially large third-party API. The underlying structure of the API is structured like this: - Home (id: 1053) - - Rugby League (id: 1054) - - - Su ...

Similar to TypeScript's `hasOwnProperty` counterpart

When working with TypeScript objects, is there a way to loop through a dictionary and set properties of another dictionary similar to how it is done in JavaScript? for (let key in dict) { if (obj.hasOwnProperty(key)) { obj[key] = dict[key]; } } If ...

When scrolling back to the top of the page, the data-spy feature does not re-highlight the "Home" anchor

After experimenting with Data-spy to change the active anchor while scrolling, I encountered an issue. Upon scrolling back up to the top of the page from the about section, the "Home" anchor failed to re-activate. How can this be fixed? I attempted to rem ...

Guidelines for submitting and displaying content on a single page with jQuery and MySQL

Objective: To develop a Q&A Script using PHP, JavaScript, and jQuery that allows users to post questions and provide answers. Upon submitting a new answer, it should be stored in the database and automatically displayed in the answers section. Challenge: ...

What purpose does tagging serve in my template for polymer property binding?

I'm currently exploring the way Polymer handles the rendering of properties in a custom element's template. I've come across some interesting behavior that I haven't been able to fully grasp yet. Specifically, I noticed that certain pro ...

Updating Ajax and selecting input fields in a form

I am currently using ajax code with jQuery and the x-editable plugin to update a select field. <a href="#" id="days" data-pk="<?php echo $id; ?>" data-url="post.php" data-title="days" data-type="select" class="editable editable-click" ...

The JQuery chosen dropdown experiences a visual issue when placed inside a scrollbar, appearing to be "cut

Good day, I've been using the jQuery "chosen" plugin for a dropdown menu, but I encountered an issue with it being located in a scrollable area. The problem is that the dropdown items are getting cut off by the outer div element. I have provided a si ...

Leveraging React Native's Async Storage to store and retrieve values consistently within the Render method

Is there a way to set and get a value in the render method with just one line of code, by using a variable between tags? I attempted this approach but encountered an error message stating "Can't find variable: storage_key". import React, { Component } ...

Incorporate an Icon for every day in FullCalendar using Angular

I am currently working with a FullCalendar and I have been exploring ways to incorporate icons into each day. Despite my efforts, including researching similar questions on SO such as: this Issue arises due to the absence of a dayRender method. this ...

Connecting an Angular2 template to a Node.js Express backend: a step-by-step guide

Seeking guidance on the integration of NodeJS/Express backend with Angular 2 frontend. Looking for assistance on how to establish connection between the two components, including any necessary configurations or code implementations. Any help would be gre ...