Show the subscription response data in Angular

When utilizing the code snippets below from two different components, I am able to receive a valid response value from the subscriber.

dataService.ts

fetchFormData(){
 return this.http.get('http://localhost:48116/RecuruitmentService.asmx/addRoleTest?i=3').map(this.extractData);
}

private extractData(res: Response) {    
 return res.text() ? res.json() : {}; 
}

app.component.ts

this.dataService.fetchFormData().subscribe((response) =>   console.log(response));

console output

https://i.sstatic.net/blH9o.png

However, when attempting to assign the response value to a variable, I encounter an 'undefined' error.

myvar:any;
this.dataService.fetchFormData().subscribe(response => this.myvar =  response);
console.log(this.myvar);

I have reviewed the following discussions. Solution-1 , Solution-2

Despite this, the issue remains unresolved. Any suggestions on how to tackle this problem?

Answer №1

The function insertappFormData() returns an asynchronous observable object. It will only be executed when you subscribe to it and you should display the result inside the subscribe() method like this:

this.dataService.insertappFormData()
  .subscribe(response => { 
    this.myvar = response;
    console.log(this.myvar);
});

Answer №2

It appears that console.log(this.myvar); is not producing the desired output because it is located outside of the subscribe function. To rectify this issue, please revise your code as follows:

this.dataService.insertappFormData().subscribe(response => {
   this.myvar =  response;
   console.log(this.myvar);
});

Please keep in mind: The subscribe function operates asynchronously.

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

How should JSON files stored on the server side be properly utilized in Next.js?

Currently, I have a collection of JSON files that I expose through an API endpoint on my web application for global access. This allows different parts of the application to retrieve the data by sending a fetch request to itself... However, since this inf ...

The element 'fontFamily' is not recognized within the 'ThemeOptions' type in MUI theming

I'm diving into the world of React and MUI by building my own dashboard from scratch. Let's take a look at my App.tsx file: import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; i ...

Troubleshooting problems with Angular 6 update through the command "ng update"

https://i.stack.imgur.com/LuPSs.png I am currently in the process of upgrading from Angular version 5 to 6. When using the "ng update" command, I encountered a problem that is shown in the attached screenshot. Can someone guide me on how to resolve this ...

Token authentication in Angular 4

I need to retrieve data from a URL after posting the username and password. However, I encounter an error when trying to get the token using the GET method. The error message is: : Response for preflight has invalid HTTP status code 405. @Component({ ...

Angular 2 and TypeScript: Mastering Checkbox Data Binding

Below is the HTML view in which user roles are checked. I want to bind a table of modified user roles using the actualizeRoles() method. How can I achieve this? <md-accordion class="example-headers-align"> <md-expansion-panel hideToggle=" ...

What is the best way to collaborate and distribute local npm packages within a shared repository across different teams?

Unique Scenario Imagine the structure of a folder as follows: /my-app /src /dist /some-library /src /dist package.json my-package.json Two npm packages are present: one for my-app and one for some-library. my-app relies on some-library. ...

Issue with Angular Material Table: Dragged rows do not drop in the correct position when scrolling

I'm encountering issues with using Angular Material Table along with Drag and Drop CDK and scrolling. While dragging a row and then scrolling, the row does not drop where intended. Additionally, the animation does not follow the scroll correctly. I ...

react dealing with clicking and blurring at the same time

Is there a way to ensure an input's onBlur event fires only after a button's onClick event is completed? The challenge is that the function relying on the state change caused by the onClick needs to be executed by the onBlur event. Using setTimeo ...

Determining the Right Version of a Framework in npm: A Guide

One common issue I encounter is the uncertainty of which versions of npm, Ionic, and other tools I should have installed. It often goes like this: "Oh, there's a new version of the Ionic CLI out. Let's update." I install CLI v3.9.0. ...

Validation of Single Fields in Angular Reactive Forms

When I validate a reactive form in Angular, I expect the error message to show up beneath the invalid field whenever incorrect data is entered. <form (ngSubmit)=sendQuery() [formGroup]="form"> <div *ngFor='let key of modelKeys&ap ...

Hide the menu when tapping outside on a tablet device

Currently working with HTML, CSS, and JS (specifically Angular) I have a Header menu that contains dropdown sub-menus and sub-sub-menus in desktop view. On a PC, the sub-menus appear on hover and clicking on an entry redirects you somewhere. Clicking o ...

NodeJS error: The 'error' event was not properly handled, resulting in a throw er

I've developed a basic web application using React, node-postgres, expressJS, and PostgreSQL DB. The app includes two input fields and a button. Upon clicking the button, the values are saved in the database. While running the ExpressJS server with ...

Is there a way to determine if a submit button has been clicked in order to prevent my function from executing?

I'm currently developing a platform for uploading images. Once a user uploads an image successfully, it gets saved in 4 different sizes within separate folders. They are then redirected to the same page with new content, where they can proceed to crop ...

Troubleshooting Problems with Angular Localization in EJ2 Syncfusion

I have been utilizing the Syncfusion Spreadsheet component to display data similar to an Excel spreadsheet. I successfully implemented all the necessary functionalities with Syncfusion documents, however, I am encountering a challenge. My current issue i ...

Developing a webpage that navigates seamlessly without the hassle of constantly refreshing with

I am in the process of creating a website that is designed to run everything within the same file, but I am unsure about how to locate study materials for this project. For example: In a typical website scenario -> If I am on index.php and I click on ...

Steps for incorporating 'admin-ajax.php' on the frontend

Here is the code for Javascript. Javascript used: new AjaxUpload('#upload_btn', { action: '<?php echo admin_url("admin-ajax.php"); ?>', This function only functions when the user is logged in. ...

``When multiple elements are clicked, the second click will remove the class

I'm struggling with jQuery. Essentially, I want the first click on "div 1" to add a class to the others and display "lorem ipsum" text, and continue this pattern for the rest. However, if I click on the same div again, the class should be removed and ...

Include web browsing history

In my ASP.Net/VB project, I am facing an issue with floating DIVs. Whenever users try to close the floating DIV by clicking on the back button in their browser, it creates a confusing experience. My solution is to add a "#" entry to the browser history wh ...

Angular: Issue encountered while attempting to differentiate an '[object Object]'. Arrays and iterables are the only permissible types for this operation

I encountered the following error message while attempting to retrieve updated data: Error trying to diff '[object Object]'. Only arrays and iterables are allowed Snippet of Get Code: allDatas allData(data) { this.allDatas = data } Up ...

What is the best method to organize HTML tables in Knockout by utilizing a Breeze navigation property?

Currently, I am utilizing Breeze.js to manage my data model within Knockout.js. This involves a simple view model with an adapter library for handling sorting tables on entity properties. The tables are sorted using tablesorter, along with a knockout bindi ...