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

Encountering CORS error when making a call to AWS API from Angular 9

Currently, I am working on implementing a post method in Angular 9 that interacts with an AWS API. However, upon calling the post function in Angular 9: this.http.post(url, body, requestOptions), I encountered an error in my browser stating: Access to XMLH ...

Guide for building a Template-driven formArray in Angular

I am currently implementing a fixed number of checkboxes that are being bound using a for loop. <ul> <li *ngFor="let chk of checkboxes"> <input type="checkbox" [id]="chk.id" [value]="chk.value&q ...

How to retrieve a value from an Angular form control in an HTML file

I have a button that toggles between map view and list view <ion-content> <ion-segment #viewController (ionChange)="changeViewState($event)"> <ion-segment-button value="map"> <ion-label>Map</ion-label> & ...

Transforming two child arrays within an object into a single array using Ramda

I am looking to transform an object into an array. The object I have is structured like this: const data = { t1: [ {"a": 1, "a1": 2}, {"b": 3, "b1": 4}, {"c": 5, "c1": 6} ], t2: [ {" ...

Is it possible to generate an array of objects, where each object includes an observable retrieved through forkJoin?

let food = { id: 1, isTasty: false } Imagine I have a custom function that takes the ID of a food item and returns an observable which resolves to a boolean indicating whether the food is tasty or not. I wish to loop through an array of food items an ...

What steps can be taken to prevent a tab click from causing issues?

Within my application, there is a tab group that contains four tabs: <ion-tabs> <ion-tab [root]="tab1Root" tabTitle="Programmes" tabIcon="icon-programmes"></ion-tab> <ion-tab [root]="tab2Root" (ionSelect)="studioCheck()" tabTitle= ...

Accept an empty string as the defaultValue, but disallow it during validation using Zod, react-hook-form, and Material UI

Currently, I am working with material ui components alongside react-hook-form and zod validation in my project. One of the challenges I encountered is with a select field for a bloodType: const bloodTypes = [ "A+", "A-", "B+", ...

Using NGRX with Angular's AuthGuard

Having trouble using AuthGuard with NGRX - I keep getting undefined on a specific route: Even though Store shows that estaAutenticado is true, I'm not able to access it in time - could this be due to async behavior? Here's my guard implementati ...

Encountering issues with compiling files in react app using webpack, failing to compile as anticipated

When it comes to compiling, I prefer using webpack with TypeScript files. In my webpack.config.js file: module.exports = async (env, options) => { const dev = options.mode === "development"; const config = { //Webpack configuration pr ...

The property of the Angular Typescript object is distinctly not defined, yet the property itself is

Currently facing a bizarre issue. Even though the console displays data in an object from a subscribed observable, TypeScript code shows it as undefined. Take a look: initData(): void { this.backendService.getData().subscribe((depotDays: DepotDayAcc ...

I encountered an issue while making customizations to my default next.config.js file. Despite attempting various solutions, I consistently encountered an error regarding the invalid src property

I'm currently trying to introduce some custom configurations into the next.config.js file. However, I keep encountering an error regarding an invalid src prop. Despite my attempts to troubleshoot in various ways, the error persists. // ...

Is there a way to position the Image component from next/image using absolute positioning?

Is it possible to use an element Image from 'next/image' with the CSS style { position: absolute; left: 50% }? It appears that it is not being applied. For example: import React from 'react' import Image from 'next/image' imp ...

Developing an Observer and sending updates to my followers

I have a function that returns an Observer for subscription. Inside this function, I make an API call which also returns an Observer to which I subscribe. Once I analyze the data received from this Observer, I need to notify my own Observer subscribers. B ...

Updating ComboBox Selection in Angular 4

When attempting to populate a combobox with the value from a selected row, only the inputs are loading. This section is part of my page: ` <form class="form-horizontal form-label-left parsleyjs" method="post" data-parsley-priority-enabled="false" n ...

Creating an Angular component to display a dynamic table using ngFor directive for a nested JSON data structure

Currently diving into Angular (version 8) and grappling with the following JSON structure {layer1 : [ { id: 'lay1', name: 'first layer', results: [ { rows: ...

Tips for denoting unnecessary non-null assertions in Typescript

Incorporated this wrapper (source) into the project I'm currently working on: export function expectToBeDefined<T>( arg: T, ): asserts arg is Exclude<T, undefined> { expect(arg).toBeDefined(); } The objective is to eliminate the usage ...

Error: Unable to locate the reference for "foo" while utilizing TypeScript in combination with Webpack

My Chrome extension is functioning properly when using JavaScript alone. However, when attempting to incorporate TypeScript with Webpack, I encountered an issue where the function foo could not be found. Uncaught ReferenceError: foo is not defined Here ...

What could be the root of this next.js build issue occurring on the Vercel platform?

I recently upgraded my next.js project to version 12.0.7, along with Typescript (4.5.4) and pdfjs-dist (2.11.228), among other libraries. Locally, everything runs smoothly with the commands yarn dev for development and yarn build for building. However, af ...

I am looking to present a nested array within an array in a tabular format

This is the structure of my database: [{ "firstName": "Shaun", "salary": [ { "id":1, "rate": 250, }, { "id":2, "rate": 290, } ] },{ "firstName": "Julian", "salary": [ { "id":1, "rate": 750, ...

Ways to retrieve a Class Level Variable within the onCellValueChanged function in agGrid

Exploring Angular with Typescript for the first time. I'm trying to access Class Level Variables within the onCellValueChanged event of agGrid, but encountering the following error: Cannot read property 'updateDict' of undefined Here&apo ...