When you sign up for the service, you might receive null values in return

I am currently in the process of subscribing to a service that needs access to the REST back-end using the specified object.

export class Country {

    iso: String;
    iso3: String;
    name: String;
    niceName: String;
    numCode: number;
    phoneCode: number;

    constructor(values: Country = {}) {
        Object.assign(this, values);
    }
}

The method in this service is responsible for fetching data from the API, and it successfully retrieves data into the map() function.

public getCountries(): Observable<Country[]> {
    return this.http.get(COUNTRY_URL).pipe(
            map(response => {
                const countries = response.json()._embedded.countries;
                return countries.map((country) => { new Country(country) });
            }),
            catchError(this.handleError)
        );
}

Below is the consumer subscribing to the service.

countries: Country[] = [];

constructor(private countryService: CountryService) {
    countryService.getCountries()
        .subscribe(countries => { 
            this.countries = countries;
    });
}

However, the country variable seems to be an array of undefined objects.

Additional Information

I am utilizing Angular 6 alongside RXJS6 and have followed the migration guide here

This snippet represents a sample API response.

{
    "_embedded" : {
        "countries" : [ ... ]
    },
    "_links" : {
        "first" : {
            "href" : "http://localhost:8080/api/countries?page=0&size=20"
        },
        "self" : {
            "href" : "http://localhost:8080/api/countries{?page,size,sort}",
            "templated" : true
        },
        "next" : {
            "href" : "http://localhost:8080/api/countries?page=1&size=20"
        },
        "last" : {
            "href" : "http://localhost:8080/api/countries?page=11&size=20"
        },
        "profile" : {
            "href" : "http://localhost:8080/api/profile/countries"
        },
        "search" : {
            "href" : "http://localhost:8080/api/countries/search"
        }
    },
    "page" : {
        "size" : 20,
        "totalElements" : 239,
        "totalPages" : 12,
        "number" : 0
    }
}

If there are any issues with my code, can someone kindly point them out? Any assistance would be greatly appreciated.

Answer №1

It appears that you forgot to include a return statement before calling new Country(country) (or you could also try removing the curly braces around it).

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

Validating properties of a class using Typescript's Class-Validator

I tried using the class-validator decorator library for validation processes on my sample project. However, it doesn't seem to be working as expected. The sample project aims to create projects based on user inputs, and I'm attempting to validate ...

Creating Separate User and Admin Navigation in Angular: Step-by-Step Guide

I am facing an issue in my Angular project where I want to segregate the admin and user navigation similar to that of an e-commerce website. However, the children route is not functioning properly for the dashboard or user sections. Whenever I click on the ...

Using the concat operator along with the if statement in Angular to make sequential requests based on certain conditions

Managing multiple HTTP requests in a specific order is crucial for my event. To achieve this, I am utilizing the concat operator from rxjs. For instance, upon receiving data from the first request, I update local variables accordingly and proceed to the ne ...

Is it possible to utilize Ionic for making an Ajax JQuery POST request?

As I try to implement NTLM authentication from my Ionic app, I have successfully tested the request using Postman. While Postman works with NTLM Authentication option, it does not offer any code for Angular (specifically for Ionic). In my research, I disc ...

Steps to ensure checkboxes are enabled for selection only when another box has been checked

Consider having 3 checkboxes: 1 'parent' checkbox and 2 'child' checkboxes. If the parent checkbox is selected, you should be able to select either or both of the child checkboxes. If the parent checkbox is deselected, neither of the ...

Which objects can be looped through in Aurelia templating?

In the documentation for Aurelia, it mentions that repeaters can be used with arrays and other iterable data types, including objects, as well as new ES6 standards like Map and Set. Map is usually recommended, as shown in the example below: <template&g ...

Utilizing the ICollection interface within Angular 6

Just starting out with Angular and I could really use some guidance on how to implement an Angular Reactive Form that will generate the JSON result shown below: { "firstName":"", "middleName":"", "lastName":"", "addressBook":[{ "addressLin ...

Fetch the JSON data and pass it to the ITest

Objective: Retrieve data from a JSON file and store it in the "test: ITest[]" array, then display it using console.log Challenge: The code is not functioning correctly. What element am I overlooking? Background: I am new to Angular Thank you! Ser ...

The types 'X' and 'string' do not intersect

I have a situation where I am using the following type: export type AutocompleteChangeReason = | 'createOption' | 'selectOption' | 'removeOption' | 'clear' | 'blur'; But when I try to compress the cod ...

Encountering an issue with Angular 13 routing where extraction of property fails when returning value as an observable

After receiving an id number from the parent component, I pass it to my child component in order to retrieve a value with multiple properties. To achieve this, I created a service that returns an observable containing the desired object. However, when atte ...

Struggling to track down the issue in my ts-node express project (Breakpoint being ignored due to generated code not being located)

For my current project, I decided to use the express-typescript-starter. However, when I attempted to debug using breakpoints in VS Code, I encountered an issue where it displayed a message saying "Breakpoint ignored because generated code not found (sourc ...

Struggling with fetching the email value in .ts file from ngForm in Angular?

I'm trying to retrieve the form value in my .ts file, but I am only getting the password value and not the email. Here is the code snippet: <div class="wrapper"> <form autocomplete="off" class="form-signin" method="post" (ngSubmit)="lo ...

VS Code using Vue is displaying an error message stating: The property '' does not exist on type '{}'.ts(2339)

While working in Visual Studio Code, I came across the following code snippet: <script lang="ts" setup> const parseCSV = () => { // Code omitted for brevity } } </script> <template> <button @click="parseCSV ...

Enhance Your Angular Experience with Console Extensions

Is there a way to include my custom schematics from npm into the Angular Console's list of available extensions? https://i.stack.imgur.com/HDuAi.png ...

The parameter type 'Event' cannot be assigned to the argument type

edit-category-component.html: <custom-form-category *ngIf="model" [model]="model" (onSaveChanges)="handleChanges($event)"></custom-form-category> <mat-loader *ngIf="!model"></mat-loader> edi ...

What steps do I need to take to resolve the issue with the coa npm library version 2.1

While working on my Angular project, I encountered an error in the console logs: Error: 404 Not Found - coa-2.1.3.tgz I have not listed this library in my package.json file and the latest version available is 2.0.2. I am unsure about what steps to take ...

What is the process for bringing in AngularJS 2? // Bring in { routerTransition } from './router.module;

Currently, I'm experimenting with implementing page transitions using Angular 2. The resources I've gone through indicate that I need to import: // import { routerTransition } from './router.module; However, despite following these instruc ...

What are the best practices for handling context in Angular?

Currently, I am focused on enhancing our code base to improve readability and performance. Our approach involves a container component that loads all necessary data and passes it down to child components via Inputs. While this is generally considered good ...

Ways to retrieve the key of an enum based on its value within Typescript

Here's an example of an enum: export enum Colors { RED = "RED COLOR", BLUE = "BLUE COLOR", GREEN = "GREEN COLOR" } Can you help me figure out how to retrieve the enum key based on a specific value? For instance, if I input "BLUE COLOR", ...

Encountering an issue connecting to the backend server for the

I am attempting to make a POST request from my Angular 2 frontend to my Spring backend, but I am encountering an error. The error message: GET http://localhost:8080/loginPost 405 () Failed to load http://localhost:8080/loginPost: No 'Access-Control ...