Steps to retrieve the value stored in a variable within an Angular service from a separate component

How can I effectively share question details and an array of options from one component to another using services? What is the recommended method for storing and retrieving these values from the service?

In my question-service class:

private static  ques_optn : Array<QnA>;
constructor() { }

public setQuestion(qna :Array<QnA>) : void
{
 qna.forEach(element => { QuestionService.ques_optn.push(element)});

}

public getQuestion() : Array<QnA>
{
return QuestionService.ques_optn;

}

In my login.ts class, I am setting the value to a variable:

 {
      ques_ans: Array<QnA> = [];
      this.ques_ans;      (contains the value)
      this.questservice.setQuestion(this.ques_ans);
    }
    In my question.ts class, I am retrieving the value:</p>

    this.ques = <QnA[]>this.questservice.getQuestion();

I aim to access the values stored in the "this.ques" variable in the question.ts class

Answer №1

Based on the inquiry, it appears you plan to utilize the service as a data storage unit... However, services are not designed to hold value;

When a component incorporates a service, it is essentially injected (and created) within the component, rendering it devoid of any intrinsic data. This means it will not retain the data you wish to globally access across various components.

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

propagate the amalgamation of tuples as an argument

I'm working with a function that returns a union type of tuples. I need to pass this return value to another function that can accept all its forms using the spread operator .... type TupleUnion = readonly [number, number] | readonly [number, number, ...

Tips for showcasing unique keywords in Ace Editor within the Angular framework

Can anyone help me with highlighting specific keywords in Angular using ace-builds? I've tried but can't seem to get it right. Here's the code snippet from my component: Check out the code on Stackblitz import { AfterViewInit, Component, ...

What is the importance of always catching errors in a Promise?

In my project, I have implemented the @typescript-eslint/no-floating-promises rule. This rule highlights code like this - functionReturningPromise() .then(retVal => doSomething(retVal)); The rule suggests adding a catch block for the Promise. While ...

What is the reason behind Angular 2's choice to implement the .ts file extension?

What is the significance of using the .ts file extension in Angular 2? ...

Is it recommended for TypeScript to automatically resolve the index.ts file as the default module file?

Struggling with getting the module resolution to work in TypeScript. Consider the following file structure: /modulename/index.ts Should it be resolved like this? import * as modulename from "modulename" I can't seem to make it work. However, imp ...

Determining the length and angle of a shadow using X and Y coordinates

I'm currently tackling the task of extracting data from a file generated by a software program that has the ability to add a shadow effect to text. The user interface allows you to specify an angle, length, and radius for this shadow. https://i.stack ...

Encountering a Javascript error while trying to optimize bundling operations

After bundling my JavaScript with the .net setting BundleTable.EnableOptimizations = true;, I've encountered a peculiar issue. Here's the snippet of the generated code causing the error (simplified): var somVar = new b({ searchUrl: "/so ...

Error in NextJS: The name 'NextApplicationPage' cannot be found

const { Component, pageProps}: { Component: NextApplicationPage; pageProps: any } = props After implementing the code above with 'Component' type set to NextApplicationPage, an error message pops up stating, The name 'NextApplicationPage&ap ...

Typescript compiler still processing lib files despite setting 'skipLibCheck' to true

Currently, I am working on a project that involves a monorepo with two workspaces (api and frontEnd). Recently, there was an upgrade from Node V10 to V16, and the migration process is almost complete. While I am able to run it locally, I am facing issues w ...

Problem with selecting dates in rangepicker

Having trouble with my recursion code for selecting dates in a rangepicker: recurse( () => cy.get('.mantine-DatePicker-yearsListCell').invoke('text'), (n) => { if (!n.includes(year)) { //if year not f ...

experiencing an excessive amount of rerenders when trying to utilize the

When I call the contacts function from the main return, everything seems fine. However, I encounter an error at this point: const showContacts = React.useCallback( (data: UsersQueryHookResult) => { if (data) { return ( < ...

Learning to utilize the i18n library with React Vite

The developer console is showing the following message: i18next::translator: missingKey en translation suche suche Here is the file structure of my project: vite.config.ts i18n.js test/ src/ components/InputSearch.tsx routes/ public/ de/translation. ...

What steps should I take to fix this Angular 8 error?

Encountered an issue in ../node_modules/@angular/http/src/backends/jsonp_backend.d.ts:1:28 - error TS2307: Module 'rxjs/Observable' not found. 1 import { Observable } from 'rxjs/Observable'; ~~~~~~~~~ ...

Creating Angular components in *ngFor loop

I have set up multiple radio button groups by dynamically populating options using ngFor within a ngFor loop. categories:string[] = [category_1, ..., category_n]; options:string[] = [option_1, ..., option_n]; <fluent-radio-group *ngFor='let ca ...

What is the reason behind tsc disregarding the include and exclude options in tsconfig.json?

I am facing an issue with my tsconfig.json file: { "compilerOptions": { "target": "ES6", "lib": [ "DOM", "ES6" ] }, "include": [ "src/server/**/*&q ...

What is the reason for instances being compatible even if their class constructors do not match?

Why are the constructors in the example below not compatible, but their instances are? class Individual { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } } class Worker { name: st ...

Tips for resolving the setAttribute() function error message: "Argument of type 'boolean' is not assignable to parameter of type 'string'"

I am currently working on a function that dynamically updates the HTML aria-expanded attribute based on whether it is true or false. However, when I declare element as HTMLElement, I encounter an error stating Argument of type 'boolean' is not as ...

const error = new TypeError(`${calculateRelativePath(cwd, fileName)}: Skipping emission of file`);

Hey there! I have a typescript code snippet that looks like this: import { getConnection } from "typeorm"; import { GraphQLClient } from "graphql-request"; import got from "got"; import database from "./utils/database&quo ...

Using the recommended Prettier plugin for TypeScript in ESLint is causing issues with the ability to use the override keyword

Software Versions: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a0f190603041e2a5d445958445a">[email protected]</a> <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7000021504041915023 ...

Error: Unable to access the property of an undefined variable in Angular 4

Here is what I currently have in my code: <p *ngIf="model.something.satisfy"> Yes </p> <p *ngIf="!model.something.satisfy"> {{model.something.comments}} </p> The issue arises in the second line with the error message "Type ...