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)
}