Why hasn't the variable been defined?

Why am I receiving an error message saying "test is not defined" in this code? Even though I have properly defined the variable in another service file, it seems to be causing issues here. Any insights on what could be going wrong?

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

@Injectable()
export class OnlineTestService {
 // please update setters and getters based on your requirements
    constructor(private http: HttpClient) {
        var test = "";
        this.getJSON().subscribe(data => {
            return data;
        });
        this.getANSWERS().subscribe(data => {
            return data;
        });

    };

    questionAnswers(input){
        test = input;
    };
    retrieveAnswers(){
        return test;
    };

    public getJSON(): Observable<any> {
        return this.http.get("assets/questions.json");
    };

    public getANSWERS(): Observable<any> {
        return this.http.get("assets/answers.json");
    };

}

UPDATE:

export class RegistrationService {
 // please update setters and getters based on your requirements
    constructor(){
        var name = "";
    }
    addUser(input){
        name = input.name;
    }
    retrieveUser(){
        return name;
    }
}

Answer №1

Your constructor defines the var test locally within its scope...

@Injectable()
export class OnlineTestService {
    test:string; //declaration at the class level
    
    // Add setters and getters as needed for your usage
    constructor(private http: HttpClient) {
        this.getJSON().subscribe(data => {
            return data;
        });
        this.getANSWERS().subscribe(data => {
            return data;
        });

    };

    questionAnswers(input){
        this.test = input;
    };

    retrieveAnswers(){
        return this.test;
    };

}

Answer №2

If you want 'test' to be a private object, it should not be declared as a variable inside the constructor. The current setup defines it as a local variable that cannot be accessed from outside the constructor.

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

Unable to locate youtube.ts file in the Angular 2 project for the YoutubeAPI integration

I've been using a youtube.d.ts file from the DefinitelyTyped project. It functions perfectly in my WebStorm while I'm editing, but once I try to run it, I encounter a 404 error stating that typings/youtube.js is not found. This file doesn't ...

Exploring dependency injection in Angular 1 using a blend of JavaScript and TypeScript

I'm currently working on integrating TypeScript into an existing Angular 1.5 application. Despite successfully using Angular services and third-party services, I am facing difficulties in injecting custom services that are written in vanilla JavaScrip ...

Extending the type of parameters in TypeScript

I am trying to call a function from my UI library with a parameter type that extends the original (Suggestion) type by adding more properties. I found a resource that suggests it is possible here: https://github.com/Microsoft/TypeScript/issues/2225 (in the ...

Triggering an event within a component to execute a specific function in another component

I am working on a component that includes multiple routes such as home, app, and navbar. My goal is to have the encrementcalc() function execute when the navbar button is pressed. I attempted to use the event emitter but was unsuccessful. Can someone prov ...

Exploring Mikro-ORM with Ben Awad's Lireddit: Navigating the Process of Running Initial Migrations

Having some trouble following the lireddit tutorial, particularly with the initial mikro-orm migration step. Encountering a similar issue as mentioned in this post. Tried modifying the constructor of the example entity (tried both provided format and the ...

An issue occurred while attempting to retrieve Firebase data using an HTTP GET request

When trying to retrieve my data from firestore using an HTTP get request, I encountered an error. It might be helpful if my data in firestore was stored in JSON format. I'm not sure if this is feasible. <!DOCTYPE html> <html lang="en"> ...

Refresh the project once logged in using angular

Thank you in advance for your response. I am facing an issue with monitoring user activity and automatically logging them out after a certain period of inactivity. I have successfully implemented this feature in my app.component.ts file, however, it only s ...

One creative method for iterating through an array of objects and making modifications

Is there a more efficient way to achieve the same outcome? Brief Description: routes = [ { name: 'vehicle', activated: true}, { name: 'userassignment', activated: true}, { name: 'relations', activated: true}, { name: &apos ...

What is the process of expanding types definitions by incorporating custom types?

I added these custom types to my project. The file structure can be found here. However, these types do not contain certain useful types such as ClientState. I want to include the following enum in those types: enum ClientState { DISCONNECTE ...

What are the steps to globalize the ng-bootstrap datepicker?

For my current project, I am utilizing the ng-bootstrap datePicker component. The demo for my simple datePicker widget can be found here. However, I am now seeking to internationalize it by setting it to use the Russian language. Any assistance with this ...

Utilizing a foundational element to automatically unsubscribe from multiple observable subscriptions

Within our Angular application, we have implemented a unique concept using a Base Component to manage observable subscriptions throughout the entire app. When a component subscribes to an observable, it must extend the Base Component. This approach ensures ...

The issue persists in Angular 5 and asp.net MVC where the ID number continues to increase despite being deleted

Currently, I am using Angular 5 (VS CODE) for the front-end and asp.net mvc/entity framework (VS2017) for the back-end. My CRUD methods are functioning properly; however, I have encountered an issue where the ID of a newly created row keeps increasing even ...

Execute the render function of the components that have been passed as

I've been grappling with a challenge lately - figuring out how to invoke a passed component's render function within another function. Let's say I have two functions named A and B: export const A = (value: any) => { return ( <div& ...

Error: Undefined Property in Angular 2 ViewChild Declaration

Exploring a simple example where the childMethod is called within the child component from the parent component using the @ViewChild() decorator. However, encountering an issue where the ViewChild variable remains undefined. Sample Child Component Code: ...

TypeScript equivalent to Python's method for removing non-whitespace characters is achieved by

I understand that I can utilize .trim() to eliminate trailing spaces Is there a method to trim non-space characters instead? In [1]: str = 'abc/def/ghi/' In [2]: s.strip('/') Out[2]: 'abc/def/ghi' I am referring to the funct ...

Can a Vue application be made type-safe without the need for transpilation?

Is it possible for Vue to be type-safe when used without transpilation (without a build step) as well? Can TypeScript or Flow be used to ensure type safety? ...

The connection named "default" was not located

Error ConnectionNotFoundError: Connection "default" was not found. I encountered this error when I implemented the dependency inversion principle in my project. ormconfig.json { "name": "default", "type": " ...

Guide to encoding an array of objects into a URI-friendly query string using TypeScript

Just getting started with typescript and looking for some help. I have an input array structured like this: filter = [ { field : "eventId", value : "123" }, { field : "baseLocation", value : "singapore" } ] The desired format for ...

Exploring the potential of lazy loading with AngularJS 2 RC5 ngModule

I am currently utilizing the RC5 ngModule in my Angular project. In my app.module.ts file, the import statements and module setup are as follows: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/plat ...

Troubleshoot: Issue with binding data from DynamicComponentLoader in Angular 2 template

My implementation involves the utilization of DynamicComponentLoader and is based on the Angular2 API Guide. https://angular.io/docs/ts/latest/api/core/DynamicComponentLoader-class.html The code structure I have set up looks like this: import {Page} fro ...