Issue with variable not being populated by Observable

Although my observable is sending back the correct object, I am facing an issue where the data is not being stored against a local variable.

import { Component, OnInit, OnDestroy } from '@angular/core';
import { LookupListsService } from '../../services/lookup-lists.service';
import { SexList } from '../../models/lookups/sexType';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})

export class RegisterComponent implements OnInit, OnDestroy {

  sexLists: SexList[] = [];

  constructor(private lookupService: LookupListsService) { }

  ngOnInit(): void {
    this.getGenderList();
    this.getCountryList();
    this.getSexList(); 
    const body = document.getElementsByTagName('body')[0];
    body.classList.add('register-page');
    body.classList.add('off-canvas-sidebar');
  }
  ngOnDestroy(): void {
    const body = document.getElementsByTagName('body')[0];
    body.classList.remove('register-page');
    body.classList.remove('off-canvas-sidebar');
  }
  getSexList(): void {
    this.lookupService.getSexList()
        .subscribe(sexlist => {
            console.log(sexlist)
            this.sexLists = sexlist
        });
  }
}

Even though I can view the object in developer tools:

{
    "sexList": [
        {
            "sexId": 1,
            "sexCode": 1,
            "sexText": "Male"
        },
        {
            "sexId": 2,
            "sexCode": 2,
            "sexText": "Female"
        }
    ]
}

However, when rendering it on my layout, I encounter the following issue:

<div><p>There are: {{sexLists.length}} records in the list</p></div>

In the console, I receive undefined for sexLists and the displayed text on the page shows:

There are: records in the list

I'm struggling to understand why the object fails to get set.

Additional service code update:

  getSexList(): Observable<SexList[]> {
    var apiURL = this.api.getApiEndPointByName('GetSex');
    console.log(apiURL);
    var sex = this.http.get<SexList[]>(apiURL);
    return sex;
  }

Answer №1

Instead of assigning an object with an array to the component, consider extracting just the array from the response using a technique like "plucking", as shown below:

  getSexList(): void {
    this.lookupService.getSexList()
        .pipe(pluck('sexList'))
        .subscribe(sexlist => {
            console.log(sexlist)
            this.sexLists = sexlist
        });
  }

(Make sure you import the pluck operator from RxJs)

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

"How can I dynamically set the text for a radio button using Reactive Forms? Also, how do I capture the selected radio button value and the question title

If I use a reactive form-array, can I dynamically add 2 questions and 3 or 4 choices? Question 1: How do I set the radio button text dynamically using form-array? Question 2: Now, I'm attempting to retrieve only the selected choice ID corresponding ...

Troubleshooting issue: Webpack dev server's Hot Module Replacement not functioning correctly when

I've been working on a Vue 2 application that is mostly JavaScript, and now I am looking to incorporate some new TypeScript modules and components into it. Everything runs smoothly when I start the webpack dev server. However, whenever I make a chang ...

What is the best way to integrate a jQuery Plugin into an Angular 5 application powered by TypeScript 2.8.1

I am trying to incorporate jQuery into my Angular 5 project using TypeScript 2.8.1. I attempted to follow Ervin Llojku's solution but it didn't work: First, install jquery via npm npm install --save jquery Next, install the jquery types npm i ...

Executing ng server with --hmr results in a continuous reloading of the page during updates

After upgrading my Angular application to version 11.0.2, I decided to give the --hmr option on the CLI a try. Although it appears enabled from the CLI, any changes made to a page still result in a complete refresh in the browser. During compilation of th ...

The custom loader for Webpack (haml-haml-loader) appears to be malfunctioning

I am fairly new to managing my own Angular applications. I found this helpful guide for setting up haml loading through webpack. However, the guide is quite outdated and ngx no longer supports eject, so I am experimenting with this package to customize web ...

What could be causing the HTTP PUT requests to stop functioning properly after a number of requests?

Currently, I am developing an app for the premier league that allows users to create their own teams, input scores for matches, and view updated team statistics in a sortable table based on the Premier League rules. Issue: I have encountered a problem wi ...

There was a mistake: _v.context.$implicit.toggle cannot be used as a function

Exploring a basic recursive Treeview feature in angular4 with the code provided below. However, encountering an error when trying to expand the child view using toggle(). Encountering this exception error: ERROR TypeError: _v.context.$implicit.toggle i ...

Can you explain the meaning of `images:Array<Object> = [];` in TypeScript?

Recently, I stumbled upon this code snippet in TypeScript images:Array<Object> = []; I'm curious, what exactly does the "<>" notation signify? ...

Setting the type of a prop dynamically based on another prop value

Consider the following scenario with an interface: interface Example { Component: React.ReactElement; componentProperties: typeof Example.Component; } Is there a way to determine the type of properties expected by a passed-in custom component? For ...

Jasmine: utilizing unit test to spy on the invocation of a nested function

When running unit tests for an Angular app, I need to spy on a function called func1 to check if it is being called. However, within func1 there is a call to func2 and I also want to spy on that to see if it is being called. How should I structure my unit ...

Develop a series of sequential tests for the playwright to execute

Can someone assist me with my code? I am attempting to write a test in Playwright that navigates to the forgot password page, creates a new password, and then tries to log in using that new password. However, I am encountering an issue with retrieving the ...

Ways to address memory leakage issues in Angular

Is there a way to manually optimize the Garbage Collector by forcefully pushing variables into it? For example, if we have a root or global level variable in an Angular component that is no longer needed when switching to another page, how can we ensure it ...

Protractor syncing with an Angular page following redirection to an Auth0 non-Angular page

My Angular web application utilizes Protractor for end-to-end tests. Recently, I implemented OAuth0 authentication into my app. To disable Angular synchronization before redirecting to the non-Angular OAuth0 page, I use await browser.waitForAngularEnabled( ...

Configuring Angular for Seamless Integration with a Backend API in Kubernetes Environment

Two separate containers, Auth and Frontend, are currently functioning independently. The next step is to establish a connection between the two in order to send and receive HTTP requests. In Angular, connections are typically made using URLs like http://l ...

I'm stuck trying to figure out all the parameters for the MapsPage component in Angular 2

Currently, I am utilizing Angular2 with Ionic2 for my mobile app development. Everything was working flawlessly until I decided to incorporate a new module for Google Maps navigation. Specifically, I am using phonegap-launch-navigator for this purpose. The ...

Unable to retrieve local property when inside a Callback function in Ionic2

I am encountering an issue with my Ionic 2 app that utilizes Angular2. It is a basic problem, but it has been quite frustrating for me. Below is the component in question... import {Component} from "@angular/core"; @Component({ '<ion-content> ...

Ensuring the safety of generic types in Typescript

Typescript is known for its structured typing, which is a result of the dynamic nature of Javascript. This means that features like generics are not the same as in other languages with nominal type systems. So, how can we enforce type safety with generics, ...

Drizzle-ORM provides the count of items in a findMany query result

Hello there, I'm currently experimenting with the Drizzle ORM and imagine I have this specific query const members = await trx.query.memberTable.findMany({ with: { comments:true } }) I'm wondering how I can retrieve the total count of me ...

Errors in typing occurring due to preact children within framer-motion

While working on my preact widget (https://github.com/preactjs-templates/widget), I noticed a connection to ReactDOM. import { motion } from 'framer-motion'; import { h, VNode } from 'preact'; const Test = () => { return <mot ...

Encountering a 403 error upon refreshing the page of my Angular 6 project

I am currently working on an Angular 6 project with JWT authorization deployed on AWS Elastic Beanstalk and utilizing CloudFront. I am using the @auth0/angular-jwt library to manage everything efficiently. The setup is functioning smoothly, and I have a li ...