Angular Http Promise is not returning the expected value

Struggling to update my component property with an HTTP result, but encountering issues. Thank you for your assistance! (currently using a static mock object)

Class - Object

export class Gallery {
    name: string;
}

Service

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Gallery } from './GalleryModel';


@Injectable()
export class GalleryLoadService {

    private galleryUrl = 'api/Gallery/Get'; 

    constructor(private http: Http) {
    }


    getGalleries(): Promise<Gallery[]> {
        return this.http.get(this.galleryUrl)
            .toPromise()
            .then(response => response.json().data as Gallery[])
            .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error); 
        return Promise.reject(error.message || error);
    }
}

Component

import { Component, OnInit } from '@angular/core';
import { Gallery } from './GalleryModel';
import { GalleryLoadService } from './gallery-services';


@Component({
    selector: 'my-gallery',
    templateUrl: 'gallery-component.html',
    moduleId: module.id 
})
export class GalleryComponent implements OnInit {
    galleries: Gallery[];

    constructor(private galleryService: GalleryLoadService) {
    }

    ngOnInit(): void {
        this.fetchGalleries();
    }

    fetchGalleries(): void {

        this.galleryService
            .getGalleries()
            .then(galleries => {
            this.galleries = galleries;
            console.log(this.galleries); <=== TypeError: galleries is undefined!!!!!
            });
    }      
}

console.log return TypeError: galleries is undefined!!!!!

API call result

[{"name":"Cats"},{"name":"Dogs"}]

Answer №1

When using the API and receiving a certain result, it is important to note that the response.json().data should not be utilized in the getGalleries method if there is no property called data. It is advised to remove the data:

.then(response => response.json() as Gallery[])

To avoid any confusion, refer to the official documentation:

Do not assume that all servers will have an object with a data property in their responses.

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

'Watch for status within resolver's state (ngrx)'

Currently, I am using a resolver that calls a standard service and returns an Observable: return this.someService.getData() .map(data=> data.json()) I am looking to replace this setup with ngrx effects and store. In the resolver, I want to dispa ...

What is the best way to retrieve a specific property from an array of objects in Angular 6 using typescript?

I am currently working on a budgeting application that incorporates an array of expenses with a price property. Each expense is defined within an Expense model in Typescript. While I can easily access the price property using ngFor loop in HTML, I'm c ...

What is the meaning of '=>' in typescript/javascript?

I keep coming across lots of '=>' in the code I found on the internet. Could someone please explain it to me as if I were 5 years old? (I'm searching for the specific code, and I'll share it here once I locate it).. Found it: ...

I am unable to utilize NavLink unless it is within the confines of the <Router> component

I am currently developing a React application using react-router-dom. To enhance the user experience with smooth transitions, I integrated framer-motion for page animations. However, I encountered an issue where my navbar was being animated and recreated e ...

Display JSON data in a table format using Angular

I have received a JSON result that looks like this: { "discipline":"ACLS", "course": [ { "value":"ACLS Initial", "classes":"0", "students":"0" }, { "BLS":"CPR Inst ...

Trouble with Angular: Passing output between child components is not working

Just dipping my toes into Angular, I started learning it yesterday for a take-home job interview project. Please excuse any rookie mistakes in advance. For some hands-on practice, I decided to work on a basic project where the main component (app) has two ...

What is the reason behind create-next-app generating .tsx files instead of .js files?

Whenever I include with-tailwindcss at the end of the command line, it appears to cause an issue. Is there any solution for this? npx create-next-app -e with-tailwindcss project_name ...

Comparing the cost of memory and performance between using classes and interfaces

As I delve into writing TypeScript for my Angular project, one burning question arises — should I use an Interface or a Class to create my domain objects? My quest is to uncover solid data regarding the actual implications of opting for the Class route. ...

Error encountered while injecting Angular dependencies in component constructor

Here is my newly created component. I am looking to allow users to adjust the count variable. import { Component, Inject } from '@angular/core'; @Component({ selector: 'app-likebtn', templateUrl: './likebtn.component.html&apos ...

Typescript Error: Trying to access a property that is undefined

I am a beginner in typescript and believe that the issue I am facing is related to typescript. Currently, I am working on an Ionic app where I have a function setwall() being called from home.html. The setwall() function is defined in home.ts. However, whe ...

How to dynamically disable a checkbox in Angular reactive forms depending on the value of another checkbox

I am attempting to deactivate the checkbox based on the value of other checkboxes. Only one of them can be activated at a time. When trying to activate one of the checkboxes, I encounter an issue where the subscribed value is being repeated multiple times ...

What sets apart the various download options for Typescript, such as npm, NuGet, and Marketplace?

While working in VS Pro, I am a beginner developer in TypeScript (as well as React and Node...). I am focused on truly understanding how these technologies integrate and function together, rather than simply copying commands and code snippets into files. ...

Perform validation on input by monitoring checkbox changes in Angular 4

I am currently working on a project where I need to loop through an array of key values in order to create a list of checkboxes, each accompanied by a disabled input field as a sibling. The requirement is that upon checking a checkbox, the corresponding in ...

The communication between my Angular 2 application and the NodeJS server seems to be experiencing issues as I

I am a beginner in the world of MEAN stack development and could really use some assistance in troubleshooting an issue. app.js const express = require('express'); const app = express(); const path = require('path'); app.use(express. ...

Retrieve data from a Firestore document in an Ionic application

I have a service that retrieves a specific document from Firestore using the getBidremains method. The method in the TypeScript class is called in ngOnInit like this: this.userInfo = this.firestoreService.getBidremains(userId).valueChanges().subscribe(da ...

I can't seem to understand why the error "bash: ng: command not found" keeps popping up even though I

Ever since I installed Angular CLI and started working with Angular, something strange happened - the ng command suddenly became not found: ng serve -o Here's a screenshot for reference: bash: ng: command not found Oddly enough, when I use the npx c ...

Creating a loading spinner with the help of an rxjs BehaviorSubject

After creating a loading spinner component for my angular 4 application to display during AJAX calls, I encountered an issue when trying to implement it with a subscription to a BehaviorSubject. This question is similar to how to show a spinner until data ...

A step-by-step guide on assigning values to an Angular Material Auto Complete component in Angular 7

Hey there! I'm currently using the Angular Material Auto complete component in my Angular 7 app and I'm trying to find a way to bind a value from an API response to it. Can someone help me out with a solution for this? HTML: <mat-form-field> ...

Update the image source dynamically upon the opening of an accordion in Angular

I have the following HTML code snippet in my file: <div class="col-md-3 col-sm-2 col-2 collapsedData" > <a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-con ...

What factors contribute to 'tslib' having more downloads than 'typecrypt'?

How is it possible that 'tslib', a library for 'typescript', has more downloads than 'typescript' itself? If one does not use 'typescript', then they cannot utilize 'tslib' as well. Just because someone us ...