Accessing information from RESTful Web Service with Angular 2's Http functionality

I am currently working on retrieving data from a RESTful web service using Angular 2 Http.

Initially, I inject the service into the constructor of the client component class:

constructor (private _myService: MyService,
             private route: ActivatedRoute,
             private router: Router) {}

To fetch data from the web service, I have added a getData() method that calls a function of MyService:

getData(myArg: string) {
    this._myService.fetchData(myArg)
      .subscribe(data => this.jsonData = JSON.stringify(data),
        error => alert(error),
        () => console.log("Finished")
      );

    console.log('response ' + this.jsonData);

In the ngOnInit method of the client component class, I invoke the getData() method (ensuring proper import and implementation of the OnInit interface):

this.getData(this.myArg);

Below is the code for the MyService service:

import { Injectable } from '@angular/core';
    import { Http, Response } from '@angular/http';
    import 'rxjs/add/operator/map';

    @Injectable()
    export class MyService {
        constructor (private _http: Http) {}

        fetchData(myArg: string) {
            return this._http.get("http://date.jsontest.com/").map(res => res.json());
        }
    }

However, I am facing difficulty in fetching the data. When I attempt to test it using

console.log('response ' + this.jsonData);
in the getData() method above, the browser displays response undefined.

Note: The attribute jsonData is a string type within the client component class.

Answer №1

When working with async http requests, it's important to remember that this.jsonData may not be set when you try to log it to the console. To ensure that you are logging the correct data, move the console log inside the subscribe callback like this:

getData(myArg: string){     
    this._myService.fetchData(myArg)
             .subscribe(data => { 
                            this.jsonData = JSON.stringify(data)
                            console.log(this.jsonData);
                        },
                        error => alert(error),
                        () => console.log("Finished")
    );
}

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

What is the correct method for embedding a javascript variable into a Twig path?

I am looking to include a variable declared in JavaScript into the path for redirecting my page. Here is my code: var id = $(this).attr('data-id'); windows.location = {{ path("mylink", {id: id}) }}; Unfortunately, I am getting an error when ...

Is there a way to attach an event for multiple arithmetic operations to a checkbox?

My form includes 4 checkboxes for different mathematical operations. <form action="" method="POST"> Select number of questions: <input type="number" name="que" value="que"> <br> <br> Select number of series: <select name="sel ...

When using Vue computed, an error is thrown stating "Issue in rendering: 'InternalError: too much recursion'" if the same key is referenced in computed

As a newcomer to Vue, I wanted to track how many times a function in the computed section gets called. To achieve this, I created the following component: const ComputedCounter = { name: "ComputedCounter", template: ` <span>{{ value } ...

Dealing with undefined properties in Javascript can cause errors

[ { dateTime: '2016-03-30 05:55:53', value: '4.0' }, { dateTime: '2016-03-30 05:55:55', value: '17.0' }, { dateTime: '2016-03-30 05:55:57', value: '17.0' }, { dateTime: '2016-03-30 06:0 ...

I encountered a parsing issue while trying to compile my Vue project

Issue: The component name "Header" should always consist of multiple words. Fix: Change the component name to a multi-word format according to Vue standards (vue/multi-word-component-names). ...

Is it feasible to access a variable outside the scope of a function if it is initially created within the scope of another function that returns a function using that same variable?

function creatPrintNumFunction() { var num= 12; return function printNum() { console.log(num); } } var printer = creatPrintNumFunction(); printer.num =13; //this part doesn't work but is there a way to access this Num variable Outside t ...

Is it possible for me to access information from an external URL using JSON?

As I delve into learning about JSON for app development, I've encountered an issue with a JSON and PHP-based chat system. While the code functions properly for the same origin policy, when it comes to sending and receiving data from an external URL, i ...

Leveraging TypeScript unions within functions to handle and throw errors

As a newcomer to TypeScript, I've encountered an odd error that I need help with. I have various objects sending data to the server and receiving fresh data back of the same object type. These objects use a shared method for sending the data, so I ap ...

The Angular Material autocomplete panel does not disappear when autocomplete is hidden within a scrollable region

Having encountered a bug, I have raised an issue for it (https://github.com/angular/components/issues/20209). I am reaching out to inquire if there exists any workaround or solution known to anyone. You can observe the problem on this demonstration page h ...

The DELETE function in express.js with MySQL integration is encountering a problem where it is unable to

As I work on setting up my website, the backend utilizes express.js to send queries to a MySQL Database. However, when attempting to delete rows, no action seems to take place. function establishConnection() { return mysql.createConnection({ multipl ...

Exploring the usage of the Date method in React

When I insert the given code snippet import React,{Component} from 'react'; import ReactDOM from 'react-dom'; import './index.css'; class Date extends React.Component{ dataToString = (d) =>{ ...

What is the best way to implement a response.write function within the request module?

I have a project where I am setting up an HTTP server and sending a request to the Yahoo Finance website to retrieve some data. My goal is to display this data on the browser, but I'm facing an issue with the response.write function not working inside ...

From creating a simple jQuery fiddle, let's delve into the world

Here is a code snippet I'm trying to transition from jQuery to an Angular directive. Visit this link to view the original code: http://jsfiddle.net/rhtr1w04/ Below is my implementation in app.js: angular.module('app',[]).directive('an ...

The jQuery AJAX request is not returning a truthy value when parsing

On my website, I am dealing with a large form and using the serialize() method to process it. However, I have encountered an issue: After completing the form, the result always returns false. I checked this using Firebug. Even though data.ok == true has ...

Separating vendor and application code in Webpack for optimized bundling

Recently, I created a React+Webpack project and noticed that it takes 60 seconds to build the initial bundle, and only 1 second to append incremental changes. Surprisingly, this is without even adding my application code yet! It seems that the node_modules ...

Tips for transferring information from Django to React without relying on a database

Currently, I am in the process of developing a dashboard application using Django and React. The data for the user is being pulled from the Dynamics CRM API. To accomplish this, I have implemented a Python function that retrieves all necessary informatio ...

Ways to prevent the need for explicit undefined checks when passing a string prop to a component in TypeScript

Can the checkVar function be modified to prevent the occurrence of an error message TS2322: Type string | undefined is not assignable to type string? // The TestComponent function takes a parameter fooProp that should be a string. function TestComponent({ ...

Discovering the worth of specific selections in a dropdown menu

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <select name="states" id="states"> <option value="100">Hawaii</option> <option value="107">Texa ...

Close the parent electron window while keeping the child window open

I am currently working on a project where I need to create an electron app that displays a splash screen initially and then opens a new window before closing the splash screen. However, despite my efforts, I am facing challenges in achieving this functio ...

Exploring the method for obtaining parameters from a generic constructor

I have a customized class called Collection, which takes another class as a parameter named personClass. I expect the method add to accept parameters that are used in the constructor of the class User class Person { constructor(public data: object) { } ...