Learn how to retrieve the return data from two combined objects using Angular's TypeScript syntax

I've encountered an issue with TypeScript syntax, specifically when a WebAPI returns a DTO containing two objects. The object being returned looks like this:

{
  "userList": [{
      "id": 1,
      "firstNm": "John",
      "lastNm": "Doe"
    },
    {
      "id": 2,
      "firstNm": "Jim",
      "lastNm": "Doe"
    }
  ],
  "selectedIds": [158, 155]
}

Within my Angular TS code, I attempted to declare users as any[], however the CLI compiler is highlighting the userList property in red and stating that 'userList' is not a member of the type of any[].

I also tried creating an interface for User with memberList: any[], but encountered the same error message. So when defining users: any[] and User[], I'm faced with the same issue.

Any assistance on this matter would be greatly appreciated.

Thank you,

getUsers() {
  this.meetingService.GetCommitteeMembersAsync(this.request.meetingId)
    .subscribe((data: any[]) => {
      var _test = data;
      this.users = _test.userList;
    });
}

Answer №1

You can expect your data to have the structure of ComitteeMembersData, with users represented by UserList

users: UserList[]; // or ReadonlyArray<UserList>
...
.subscribe((data: ComitteeMembersData) => {
 // perform actions here
}



export interface ComitteeMembersData{
    userList:    UserList[];
    selectedIds: number[];
}

export interface UserList {
    id:      number;
    firstNm: string;
    lastNm:  string;
}

Answer №2

Here is the data format you can expect:

{
  "userList": [{
      "id": 1,
      "firstNm": "John",
      "lastNm": "Doe"
    },
    {
      "id": 2,
      "firstNm": "Jim",
      "lastNm": "Doe"
    }
  ],
  "selectedIds": [158, 155]
}

This data can be of type any, not specifically an any[]. However, data.userList may still be an array of any. To resolve any issues, follow these steps:

users: any[];
...
getUsers() {
  this.meetingService.GetCommitteeMembersAsync(this.request.meetingId)
    .subscribe((data: any) => {
      this.users = data.userList;
    });
}

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

Injection of environmental variables into app services

Through the use of Nx, I have created multiple apps that each have their own environment with different API URLs. The Nx Workspace library includes shared services that are utilized among all apps, however, it is necessary to pass the environment-api-url w ...

What are the benefits of incorporating component A into component B as a regular practice?

I am considering creating an instance of Component A within Component B, but I'm unsure if this is a best practice in Angular or if it will just cause confusion. Component A: This component generates a modal window asking the user to confirm file de ...

What are the differences between TypeScript's 'Dictionary' type accessors for objects and objects with predefined members?

Currently, I am delving into TypeScript by following an online tutorial. While my programming background primarily consists of 'structurally' typed languages like C and ActionScript 3, TypeScript presents some new concepts for me to grasp. One p ...

Angular component testing encountering undefined NgZone

I am facing a challenge while testing for bad input values in an Angular Date Range picker component that I am developing. In my ngOnInit() function, I include a check for minimum and maximum date values. However, when attempting to write a test case for ...

Leveraging external JavaScript libraries in Angular 2

Having some trouble setting up this slider in my angular2 project, especially when it comes to using it with typescript. https://jsfiddle.net/opsz/shq73nyu/ <!DOCTYPE html> <html class=''> <head> <script src='ht ...

Obtain a 404 error status code when the route cannot be found in Angular 6+ using Universal

After launching my project with Universal, I set up my .htaccess file to direct all requests to the index.html, which serves as the root page for my Angular application. I followed the instructions on https://angular.io/guide/universal to enable sharing l ...

Ways to display a US map using d3.js with state names positioned outside each state and pointing towards it

Currently, I am working with d3.js and d3-geo to create a map of the USA. My goal is to display the names of some states inside the state boundaries itself, while others should have their names positioned outside the map with lines pointing to the correspo ...

Error encountered: TypeScript module 'angularfire2/interfaces' not found in Ionic 3 with angularfire2-offline plugin

Encountering an error while trying to set up angularfire2-offline: [16:02:08] typescript: node_modules/angularfire2-offline/database/database.d.ts, line: 2 Cannot find module 'angularfire2/interfaces'. L1: import { Angula ...

Encountering Error 404 while submitting a form on Prisma, Axios, and NestJS

Currently, I am working on a Sign Up page using SolidJs and NestJS with Prisma. However, when I try to submit the form, I encounter an error that says POST 404 (Not Found) and this error is also returned by axios. Additionally, my setup includes postgres ...

Having trouble executing my Node.js project written in Typescript due to an error: TypeError [ERR_UNKNOWN_FILE_EXTENSION] - the file extension ".ts" for /app/src/App.ts is unrecognized

After attempting to launch my application on Heroku, I encountered the following stack trace. The app is a basic ts.app using ts-node and nodemon. I am eagerly awaiting the solution to this issue. 2020-05-30T00:03:12.201106+00:00 heroku[web.1]: Starting p ...

The exported variable 'SAlert' is utilizing the name 'AlertInterface' from an external module

Utilizing the antd alert component (ts) with styled components import styled from 'styled-components'; import Alert from 'antd/es/alert'; export const SAlert = styled(Alert)` && { margin-bottom: 24px; border-radiu ...

Exploring the potential of Socket.io and Angular with the seamless integration of

I have encountered an issue regarding the use of async pipe with Observables. Initially, I assumed that returning an Observable from my service on a socket.on event would suffice. However, it appears that my approach is incorrect. Can you guide me on the c ...

Transition Angular 2 Release Candidate to production environment

As we continue working on our web application using Angular 2 RC, I am curious about the feasibility of upgrading to the final version of Angular once it is released. Is it possible to seamlessly upgrade the Angular JS Framework in our production environ ...

The combination of Angular2, TypeScript, and moment.js is lacking in terms of available locales (only 'en' is supported)

Currently, I am following a tutorial in a book to grasp the concepts of TypeScript and AngularJS 2.0:(Become_a_Ninja_with_Angular2). In one section, the tutorial walks through creating a custom Pipe and demonstrates an implementation using moment.js. To ...

TypeORM issue - UnsupportedDataTypeError

Here is the entity file I'm working with, user.ts: @Entity('users') export class User { @PrimaryGeneratedColumn() id: number | undefined; @Column({ type: 'string', name: 'username', nullable: true }) username: s ...

What are the common issues with Angular 2's ng-if directive?

I am completely new to working with Angular and have already gone through all the ng-if related questions without finding a solution that fits my issue. Here is my code: <tr *ngFor="#position of positions"> <td> ...

I have to make sure not to input any letters on my digipas device

There is a slight issue I am facing. Whenever I input a new transfer of 269 euros with the bank account number BE072750044-35066, a confirmation code is required. The code to be entered is 350269. https://i.stack.imgur.com/YVkPc.png The digits 350 corres ...

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 ...

Extract data from a string and assign it to a variable representing an

I have a custom function that parses a string and converts numbers and boolean values to their appropriate JavaScript primitives. This function is specifically designed for working with query parameters: const parseQueryParams = (searchString: string) => ...

Unleash the full power of Angular Components by enhancing them with injected

I am facing a challenge with handling the destruction event of an Angular component in my external module that provides a decorating function. I've run into issues trying to override the ngOnDestroy() method when it includes references to injected ser ...