I find that the value is consistently undefined whenever I attempt to set it within a promise in Angular

Hi there, I've encountered an issue with my getData() function in accountService.ts. I'm attempting to fetch user data and user account data simultaneously using a zip promise. Although the resolve works correctly and I receive the accurate data, I am facing a problem where the local variables I set to store the returned values always end up as undefined. My intention is to be able to use these variables in other functions.

getData(){
    zip(this.getUser(), this.getAccount()).toPromise().then(data =>{
        this.user = data.values[0];
        console.log(this.user);            
        this.account = data.values[1];
        resolve(data.values[0],data.values[1]);
     });         
}

I'm working with Angular 8 using typescript.

Thank you!

Answer №1

It appears that your function getData() is not returning any values. Here is a suggested approach:

getData(){
    return zip(this.getUser(), this.getAccount()).pipe(
      tap(data => {
        this.user = data.values[0];
        this.account = data.values[1];
      }),
      map(({user, account}) => ({user, account}))
    )       
}

Now, we are returning an

Observable<{user: any, account: any}>
. In the component where this function is utilized, access the values using subscribe:

ngOnInit() {
  this.accountService.getData().subscribe({
    next: data => {
      // Access account using data.account and user using data.user
    }
  })
}

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

Looking for a method to call a child component's function through a click event triggered from the parent component?

How can I trigger a specific function in my child component from a click event in my parent component? Any assistance would be greatly appreciated! ...

What is the solution for the error "does not exist on type 'HTMLTableDataCellElement'" in Angular?

When working on my Angular project, I implemented a PrimeNG p-table component. <p-table [value]="users" class="user-roles-table" [rows]="5" [showCurrentPageReport]="true" [ ...

I've tried using a ControlValueAccessor, but for some reason the value isn't getting passed to the form

Currently, I am experimenting with reactive forms in Angular, and I'm encountering difficulties with updating the form from custom components. As an example, take a look at the date-input component created using flatpickr in the linked Plunker demo. ...

I designed a dropdown menu with a searchable <mat-select> feature, where selecting an item is automatic when a space bar is pressed in the search box

Description : I have implemented a dropdown list using element that contains a list of items along with a search field. This allows users to easily search for specific items in the list instead of manually scrolling through a long dropdown menu. They can ...

Exploring the Powers of Typescript Interfaces within Interfaces

Can you assist me with implementing an interface wrapped within a second interface? Here is the code snippet for the reducer: import { createSlice } from '@reduxjs/toolkit'; export interface IStep { id: number; label: string; value: string ...

Merging Two mat-error Elements in Angular

I recently dived into the world of Angular by following their official tutorial. Curiosity got the best of me and I started experimenting with error handling using Angular Material when a user enters their email. I'm wondering if there's a way to ...

Unable to alter the height of the element

I am attempting to resize an element by dragging, similar to this example. I have created a simple directive for this purpose: @Directive({ selector: '[drag-resize]' }) export class DragResizeDirective { private dragging: boolean; const ...

What is the best way to showcase a half star rating in my custom angular star rating example?

component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { projectRating ...

How can I toggle the visibility of a div after the DOM has finished loading?

I was experimenting with a radio button on the interface linked to a property in the typescript file that controls the visibility of another div. However, I noticed that both *ngIf="isFooSelected" and [hidden]="!isFooSelected" only function upon initial pa ...

Issue: The inject() function can only be executed within an injection context. Issue: An untruthy value was expected to be truth

I'm currently in the process of setting up a unit test for my app.component. I've imported all the necessary components, but I keep encountering an error that's puzzling me. I activated "preserveSymlinks": true in my angular.json file, but t ...

How to Add RouterModule to an Angular 10 Library without Ivy

I am developing a custom Angular 10 Library to be shared on a private NPM repository. I followed the instructions from Angular.io and used ng new my-workspace --create-application=false and ng generate library my-library with Angular CLI. In one of the co ...

What is the best way to extract subscribed data from a function in Angular 2?

I'm currently working on a function that makes multiple API calls using for loops. My goal is to combine all the responses and return them once the last API call's data is received. Although I can successfully combine the data within the functio ...

The incorrect argument is being used to infer the generic type

I have implemented the NoInfer feature from the library called ts-toolbelt. However, it seems that the example provided below does not reflect its intended effect. In this scenario, the generic type is deduced from the util function as soon as it is intr ...

Troubleshoot Angular2 modules efficiently using source mapping features

Is there a way to debug Angular2 module code using TypeScript source mapping in the browser? After installing my project with the "npm install" command following the steps in https://angular.io/guide/quickstart, I noticed that while source mapping is ava ...

How should one properly address an HTTP error situation?

Present situation: I am currently working on a service.ts file that saves data in the backend: public update(route: string, values: Array<any>): Observable<boolean> { let body = { values: values }; return this.httpClient.put(route, bo ...

actions with frontend routing for CRUD operations

Imagine you are creating a simple CRUD todo application. Whether you choose to use Angular, React, or Vue for routing, the setup will be similar: /todos => see all todos /todos/:id => view one todo by id /todos/:id/edit => edit one todo by id /t ...

Best practice for Angular: Efficiently storing application settings retrieved from API

I'm working on an application where I need to initialize the settings and data for the application. This includes forms data with validation rules, dropdown options, and potentially other settings to be determined. What is considered the best practic ...

TypeScript Library encounters issues when importing a specific data type

I recently integrated a library into my Next.js application to manage layouts using useState in react-grid-layout. To make this work with TypeScript, I had to install the necessary package shown below: npm install --save @types/react-grid-layout The code ...

Jest encountered an error while attempting to parse the TypeScript configuration file

I've been working on setting up Jest with Babel and Typescript, following the guidelines provided here. However, when I run npm run test, I encounter the error message: Error: Jest: Failed to parse the TypeScript config file C:...jest.config.js` Th ...

Troubleshooting issues encountered while sending HttpClient Get Requests from Angular Front-End to Node.js Back-End

I am encountering an issue where I keep getting the error message "Cannot GET /" on my local host URL when attempting to send a HttpClient get request from my Angular front-end to my Node.js back-end endpoint. Despite the fact that my back-end endpoint suc ...