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

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

Extracting Information from ASP.Net Web API using Angular 4

After experimenting with the well-known Visual Studio 2017 Angular 4 template, I successfully tested the functionality of side navbar buttons to retrieve in-memory data. I then proceeded to enhance the project by adding a new ASP.Net Core 2.0 API controll ...

The user score tracking database, cataloging personal scoring history

In my database, I have a table called User. Each user in this table has a field named score. I am looking to display how the score of each user has evolved over time. My dilemma is whether to store this score separately. Should I create a new database t ...

The JSON object was not found in the AJAX response

I received a JSON object through an AJAX request. When I use console.log(response); in the console, I can see my object. However, when I use console.log(response.mostSearched);, it returns undefined. Why is that? I copied the object from the devTools con ...

The 404 error message was encountered when attempting to fetch the Ajax

I am experimenting with using Ajax to load all images from a local folder onto my HTML page. The code I am referring to comes from this question. I am running the files on a (Tomcat 8.5) server in Eclipse and opening the URL in Google Chrome. However, when ...

Strategies for organizing your week with a calendar

Hello, I am working on creating a weekly calendar using PHP and I want to add events to the calendar like in this example. However, I am unsure how to display the events in the calendar at the correct time of day. Here is the code snippet I am currently u ...

Hold off on advancing until the particular text is found in the DOM element

One of the challenges I'm facing is creating a function that waits for specific text to change before returning a value: function getElementText() { while(isLoading()) { } return $('#element').text(); } function isLoading() { ...

Why is Mongoose returning null when using findOne?

Here is a sample request: interface IGetFullnameRequest extends IAuthenticatedRequest { readonly body: Readonly<{ fullname: string; }>; } This is the controller function to get the fullname: const getFullname = async (req: IGetFullna ...

Issue with separatorKeys functionality in ng2-tag-input

I've been experimenting with the ng2-tag-input module using a simple configuration: import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'search-form', template: `<tag-input [( ...

Tips for displaying a Rails action without a layout in html format using Ajax

Is it possible to render the new action without the application layout and without altering the current code structure? class FoobarController < ApplicationController def new @foobar = Foobar.new end # ... end When a user clicks on = link_ ...

Vue Single Page Application - invoking methods across all components

I am currently developing a notification feature that can be triggered from any component. It utilizes a straightforward Vuetify v-snackbar. Within App.vue <router-view :key="$route.fullPath"></router-view> <v-snackbar :valu ...

"Unsuccessful jSON request made by Ajax resulting in undefined response

I've implemented an ajax call to fetch data from a json file and display it in an HTML table. Everything was working fine initially, but now it seems to be returning UNDEFINED. Could it be that the data from the json file hasn't finished loading ...

Using jQuery to Filter Nested JSON Data with Multiple Record IDs

Here are some links for reference: Revision link Filter JSON Data with multiple record IDs in jQuery I'm struggling with implementing filters for hierarchical data in JSON. I've made some modifications to the filterStore function, but it' ...

Serialization and encoding using json.NewEncoder and json.NewDecoder

I am currently delving into Backend development by constructing a very basic REST API using the gorilla mux library in Go (referring to this tutorial) Here is the code that I have developed so far: package main import ( "encoding/json" "ne ...

The maximum property in a Mongoose schema does not have any impact or

const mongoose = require("mongoose"); const PostSchema = new mongoose.Schema( { user_id: { type: String, required: true, }, content: { type: String, max: 150, required: true, }, }, { timest ...

Every attempt to connect with the webservice via an ajax call has ended in failure

I am encountering an issue with a webservice call that I am making using jQuery's AJAX method. Despite receiving JSON data from the webservice when accessed directly through the browser, my site always triggers the error function rather than the succe ...

Using HTML, CSS, and JavaScript, the main tab must include nested subtabs to enhance navigation and

When a user clicks on a tab, another tab should open within the main tab. Depending on the selection in the second tab, input fields should appear while others hide. Something similar to the nested tabs on expedia.com. I have experimented with the tab vie ...

Retrieve the value of a dynamically generated input element within a form object

I'm trying to figure out how to reference a dynamic 'name' of an input element in a form. Can anyone help? Here's an example using HTML: <form> <input type="text" name="qty1" value="input1" /> <input type="text ...

What is the process for renaming folders with files in node.js?

The current method is effective for renaming a single folder with no files, but it fails when trying to rename a folder containing one or more files. const handleRenameFile = () => { const oldPath = `./${directory}/${fileName}`; const newPath = ...

Create your own unique Semantic UI themes using the Semantic UI theme builder, complete with support for Font Awesome classnames and the ability to preview them with the

My admiration for Semantic UI and Semantic UI React knows no bounds. Not only are they phenomenal libraries, but their documentation is truly a work of art. Yet, crafting and keeping up with themes for these components can be quite the challenge. The task ...

Is it possible for CSS to prevent the insertion of spaces?

When filling out a form, I am able to insert spaces in inputs but not in the textarea (which is necessary). Interestingly, inserting spaces in the textarea works flawlessly. <form action="/#wpcf7-f519-o1" method="post" class="wpcf7-form" enctype="mu ...