The concept of asynchronous programming in Typescript and its implications on the

I've created a basic service to retrieve information from a database. The service is functioning properly, but I'm encountering an issue when attempting to transfer the data from the service to a component using an async function. It seems that I am unable to pass the scope of the function using "this." Any suggestions? I'm new to development so there might be something obvious that I'm missing.

Below is the service code, which is working fine:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class VenueserviceService {

  constructor(private http: HttpClient) { }

  httpGetFeatures() {
    console.log("inFeatures")
    this.http.post("http://******************",
  {
         "command": "get_feature",
         "classes":"F,G"
  })

  .subscribe(
         (val) => {
        console.log("inSubscribe")
        console.log(val)
          return(val)
         },
         response => {
         console.log("POST call in error", response);
         },
                 () => {
  });
  }



  parseFeatures (val: any) {
    console.log("in parse Features")
    console.log(val)
  }
}

And here's the TypeScript code for the component. The error occurs with "this" being undefined, as I believe the scope of it is not being passed through. It happens in the final async function at the end.

import { Component, OnInit } from '@angular/core';
import * as data from "./testfile.json";
import * as catdata from "../categories/cattestfile.json";
import {VenueserviceService} from "../../services/venueservice.service";

@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {

  constructor(private venueService: VenueserviceService) { }

  panelOpenState = false;
  title = 'Cotswolds Destinations';

  venues: any = (data as any).default;

  categories: any = (catdata as any).default;

  formatLabel(value: number) {
    if (value >= 1000) {
      return Math.round(value / 1000) + 'm';
    }
    return value;
  }

  value = 'Clear me!';

  ngOnInit(): void {
    console.log("Homepage Start");
    console.log(this.categories);
    console.log(this.venues);
    console.log(data);
    console.log(this.venues.name);
    for(var i=0; i < this.venues.length; i++){
      console.log(this.venues[i]);
    }
    console.log("Homepage End");
    
    let categories = this.venueService.httpGetFeatures();
    console.log(categories);
  }
}

const getData =  async () => {
  const data  = await this.venueService.httpGetFeatures()
  console.log(data)
}

Answer №1

Here's a suggestion for you to try:

Retrieve Data Service

    fetchData() {
        console.log("Fetching data")
        return this.http.post("http://examplewebsite.com:8443",
        {
            "command": "retrieve_data",
            "types":["A","B"]
        })
    }

Data Display Component

displayedData:any;
const displayData =  async () => {
  this.dataService.fetchData()
    .subscribe( response => { this.displayedData = response });
}

Answer №2

Firstly, there is no return statement in the VenueserviceService.httpGetFeatures method since its return type is void.

Secondly, your getData lambda function expects a promise due to your async-await syntax. You can either modify it as follows:

httpGetFeatures() {
  return this.http.post("http://cotswoldsdestinations.co.uk:8443",
  {
    "command": "get_feature",
    "classes":"F,G"
  }).toPromise();
}

Or you can simply subscribe to the returned observable without using await:

httpGetFeatures() {
  return this.http.post("http://cotswoldsdestinations.co.uk:8443",
  {
    "command": "get_feature",
    "classes":"F,G"
  });
}
const getData = () => {
  this.venueService.httpGetFeatures().subscribe(data =>
    console.log(data);
  );
}

If you have defined getData within a component that has

venueService: VenueserviceService
injected into its constructor via DI, everything should work correctly.

To ensure proper functionality, make sure to define getData as a member of the Home page component's class like so:

export component HomePageComponent {
  constructor(private venueService: VenueserviceService) {}

  getData() {
    this.venueService.httpGetFeatures().subscribe(data =>
      console.log(data);
    );
  }
}

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

Ways to stop click function execution in jQuery

Here is the HTML code I am working with: <h4 class="milestonehead" style="cursor: pointer;" onclick="editFun('35');"> Some Header <img src="/images/delete.gif" style="float: right;" onclick="deletefun('35');"> < ...

Determining the presence of a class while a tab is active using Cypress.io

Looking for a way to determine if Test1 or Test2 has been clicked in the HTML code below: <div> <li><a class="class1 active">Test1</a></li> <li><a class="class1">Test2</a></li> < ...

Animate the jQuery display property to show a table without changing any specified spatial dimensions

When utilizing jQuery's $.animate() on an element styled with display:table, any spatial dimensions that are not explicitly specified to change will animate. Check out the fiddle here In the scenario presented, the width is defined for animation, bu ...

Establish a connection between the MySql database in WHM (phpmyadmin) and a node.js application

Our team has been working on setting up the database connection with Mysql using node.js in Cpanel. Although I didn't create the database myself, I have all the necessary information such as the host, user, password, name of the database, and port nu ...

Prevent the Esc key from closing panel in jQuery Mobile

As per the jQuery Mobile documentation: "If you click the link that opened the panel, swipe left or right, or tap the Esc key, the panel will close. By default, panels can also be closed by clicking outside of the panel onto the page contents." Visit t ...

Deactivate a single choice within the select field while allowing the rest to remain active

I am facing a challenge where I have two select elements with the same options. My goal is to disable an option in one select element if it has already been selected in the other select element. Below are my two select elements: <select class="form-co ...

What methods does Angular2 use to differentiate between Light DOM and Shadow DOM within component views?

Currently, I'm engrossed in an intriguing article that delves into the concepts of host and visibility. In particular, it sheds light on the significance of the viewProviders metadata property within the Component decorator: The article discusses h ...

Is it possible to delete an item from both the input button and the list?

Asking for help with an issue -> https://stackblitz.com/edit/dropdown-fill-empty-uecsjw?file=src%2Fapp%2Fapp.component.ts Current problem description. The issue I am facing is that after selecting items from a drop-down menu and then deleting them usi ...

Unable to sort dates using arrays on IOS

Currently, I am retrieving data from my server and storing it in a variable named "items". Whenever I execute the following code: if (this.items) { this.items.sort(function (a, b) { return +new Date(b.datum) - ...

Adjust the horizontal position of the background by +/- X pixels

Is there a way to adjust the background-position by a specific distance, say 20px, from its original position? For example: $(".selector").animate("slow").css("backgroundPosition", "center -=20px"); (Unfortunately, this approach doesn't yield the d ...

The input element doesn't show the value when generated by an Angular Directive

I have developed a custom directive that enables me to replicate some HTML with an input field. However, the issue arises when the input is rendered, as the value field gets populated with the value from the scope but does not appear on the screen. This p ...

How can I retrieve the latitude and longitude of a marker after it has been moved in @angular/google-maps?

i'm currently working with the @angular/google-maps official component in Angular. One issue I'm facing is retrieving the lat and lng values of a newly added marker: my implementation mirrors this example . However, I am struggling to update the ...

Utilizing lodash and Angular 8: Identifying an valid array index then verifying with an if statement

In my current project, I am developing an e-commerce angular application that includes a basket with two types of products: restaurant + show combos and gift cards. When a client reserves a restaurant, they must also reserve a show; conversely, the client ...

The NestJS server encounters an unhandled exception leading to a server

As a newcomer to Nest.js and in the process of building a REST API server with typeorm, I have encountered an issue related to async functions. If I forget to include the await keyword while using an async function, it may result in an exception like &apos ...

Tips for including markers on Google Maps once the map has finished loading:

Currently, I am developing a phoneGap application and going around my house to gather coordinates: var locations = [ {lat:123.12313123, lng:123.123345131}, {lat:123.12313123, lng:123.123345131} ] While referring to the documentation here, everything ...

Clicking on the response from the GET request to view the data in a separate browser tab

I'm having difficulty figuring out how to use Ajax and JQuery to send a GET request with data parameters and display the response in a new browser tab. Here's an example of what I'm trying to accomplish: $('#test-button').on(&apos ...

Using CSS to design a table-like structure with rows that span multiple columns

I am trying to generate a table dynamically using CSS and a JSON array. For example: In the code snippet provided, I have assigned a class of 'spannedrow' to span certain cells in the table, although the class is not defined yet. This is just ...

Error in Express.js App: Attempting to access properties of an undefined object (specifically 'transfer-encoding')

Currently, I am developing a blogging app API using express and MongoDB. In my project, I want to include an image for each blog post. However, as someone who is new to express, I encountered a specific issue that has been puzzling me. The error message ...

Ensuring Type Compatibility Between Classes and Object Literals in TypeScript

When working with TypeScript, it is important to note that an object literal can be assigned to a class typed variable as long as the object provides all properties and methods required by the class. class MyClass { a: number; b: string; } // The co ...

The absence of data in a c# web api controller is causing issues with jQuery AJAX post requests

When I am sending data to a c# web api controller, I use the following method: $.ajax({ type: "POST", url: "menuApi/menu/Cost", data: JSON.stringify(order), contentType: "application/json", success: function (data) { window.alert(&apo ...