"When using Angular9's http.get() method, it sometimes returns undefined

I have been researching this topic further, but none of the solutions provided have helped me. I am attempting to make an http.get() request in Angular using a URL from Firebase: https://firestore.googleapis....

Despite successfully receiving JSON data through the URL, I have been unable to retrieve it in my code. Here is the approach I am currently trying:

import { Injectable } from '@angular/core';
// install rxjs first: npm install rxjs-compat --save
import { Observable } from 'rxjs/Observable';
import { BookModel } from '../../models/book/book.model';
import { Subject } from 'rxjs/Subject';
import { AngularFirestore } from '@angular/fire/firestore';
//import { AngularFirestore } from 'angularfire2/firestore';
// se non presente: npm install @angular/http@latest
import { Http } from '@http/http';
//import { HttpClient } from '@common/http'; 
import { map } from 'rxjs/operators';


@Injectable({
  providedIn: 'root'
})
export class CartService {
  private emitAddToCart = new Subject<any>();
  addEmitted$ = this.emitAddToCart.asObservable();
  // http requests (https://firebase.google.com/docs/firestore/use-rest-api) example of httprequest
  hardCodeUrl = 'https://firestore.googleapis.com/v1/projects/angularfirebasegb/databases/(default)/documents/cart?key=AIzaSyDNW48hAmvH8eAZpbeflRKb0khY5Blzsqg';
...

When calling service.httpCall() from another class, it returns "RISULTATO undefined". I attempted to call

return this.http.get(this.hardCodeUrl);
as follows:

service.httpCall().subscribe(data => {
  responseFromBackEnd = data;
});

However, the response still remains undefined even after parsing it in the following way:

let jsonFromBackend = JSON.parse(responseFromBackEnd.text());

This results in an error due to the undefined value. Update: By implementing

return this.http.get(this.hardCodeUrl).subscribe(result => {
    console.log("RISULTATO", result);
});

An object like the following is returned:

https://i.sstatic.net/PxRKV.png

and .text() yields an empty value

Answer №1

Your current implementation using the map operator in your map pipe .pipe(map(data => {})) is causing it to return undefined:

return this.http.get(this.hardCodeUrl).subscribe(result => {
    console.log("RESULT", result);
});

This setup will output each object individually.

The purpose of the map operator is to apply a specific project function to every value emitted by the source Observable and then emit these transformed values as an observable. In your case, you are receiving each value but returning an empty object as the output.

A better approach would be to return the Observable directly from the service:

httpCall() {
   return this.http.get(this.hardCodeUrl);
}

You can then subscribe to this Observable from any components that require these values:

this.service.httpCall().subscribe((res) => {
   console.log("Response", res);
});

If you need to perform any transformations, you can do so within the server's logic and return the modified Observable:

httpCall() {
  return this.http.get(this.hardCodeUrl).pipe(
    map((res: { documents: any }) => {
      return res.documents;
    })
  );
}

This will return an observable containing the values of the "documents" property from the original response.

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

Utilize zimJS within an Angular 4 application written in Typescript

After extensive searching, I have come up empty-handed in my quest to find the answer. There are no modules available for zimjs, only for createjs, but I require the entire package. I have exhausted all resources and still cannot find a solution. I am ke ...

What is the best method for connecting an Angular 2 application with an existing Angular JS app?

I recently created an application using Angular 2 and now I am looking to combine it with an Angular JS app. ...

Unable to locate the _app.js file within my Next.js project

After using "npx create-next-app" to set up my NextJs project, I came across a situation where I needed to define TransactionContext in _app.js. However, I encountered the issue that this file is not included in my project. Any assistance would be greatly ...

Can RESTKit effectively replace ASIHTTPRequest?

After relying on ASIHTTPRequest for a significant amount of time and being quite satisfied with it, I now find myself in a position where I need to consider replacing it as it has been deprecated. Initially, my instinct was to switch to NSURLConnection, bu ...

How can we transfer a value from a parent component class to a child subclass?

In my TypeScript file, there are three classes within a single file. I am attempting to transfer a value from the MainComponent class to the TableContent class. I initially tried using super() inside the TableContent class which did not work, and then att ...

Executing an Angular 4 script using a scheduled CRON job

We are currently facing a challenge with our Angular-built APP for Android phones. The logic has become quite intricate and we have decided to transfer it to our server, where it can be executed as a CRON job every hour instead of within the Phone APP it ...

Angular static dropdown option

<input [formControl]="twitterHandle" id="twitterHandle" placeholder="twitterHandle"> Fetching the input value from the Twitter handle input field using the following code: twitterHandle = new FormControl(); this.twitterHandle.value; Similarly, if ...

"Troubleshooting Problem with Closing Drawer Function in Material-UI Drawer

I have been implementing Material-UI in my React Project and am working on creating a component that will render a drawer with some additional components inside it. However, I am encountering several issues with the open drawer functionality. I initially t ...

Encountering deployment problems with React and TypeScript involving router on Github Pages

After successfully running locally, I encountered a 404 error when deploying the website using "npm run deploy." My application is built with React and TypeScript, utilizing react-router-dom BrowserRouter for navigation between pages. I've spent 7 h ...

Using the <head> or <script> tag within my custom AngularJS2 component in ng2

When I first initiate index.html in AngularJS2, the structure looks something like this: <!doctype html> <html> <head> <title>demo</title> <meta name="viewport" content="width=device-width, initial-scal ...

Duplicate request detected for ASIHTTPRequest

Recently, I began using ASIHTTPRequest for my iOs app and encountered a minor problem. It seems that all requests are being sent to the server twice, even though only one response is received by the delegate methods. This issue persists with both synchron ...

Sending a parameter to a confidential npm module

I've developed a custom npm module that can be used in my applications by including this code snippet in the HTML: <app-header-name></app-header-name> Here is the TypeScript code inside the npm package: import { Component, OnInit } from & ...

Steps to create a persistent bottom modal with scrollable content

I'm currently using Bootstrap 4.6 within my Angular application. I have implemented a modal that expands to full-screen on mobile devices, and now I want to add a fixed footer with scrolling body content. I've attempted to adjust the height of t ...

Using Angular2 observables to parse JSON with a root element

I am completely new to working with Angular observables and I find myself a bit bewildered by how it all functions. Recently, I was handed an Angular CLI application that is mostly operational, but now I need to connect it to my existing API. Within my se ...

Swap out the traditional for loop with a LINQ query utilizing the any method

In my TypeScript code, I have the following snippet: public executeTest(test: Test): void { const testFilters: Record<string> = getTestFilters(); let isTestingRequired: boolean = false; for (let i: number = 0; i < testFilters.leng ...

Declaration files for Typescript ESLint configurations

I've been researching this issue online, but I haven't been able to find any solutions. It could be because I'm not entirely sure what's causing the problem. What I'm trying to do is set a global value on the Node.js global object ...

What is the best way to verify nested objects with a generic type?

Consider a scenario where I have a generic type defined as follows: type Item<T> = {a:T; B:T} In this case, I aim to automatically determine an object with consistent fields types without explicitly stating the generic type: const items: Record<s ...

It is feasible to completely override a class in TypeScript

I have a subclass defined as follows: customException.ts /** * Custom Error class. * * @class Error * @extends {Error} */ class Error { /** * @type {string} * @memberof Error */ message: string; /** * @type {boolean} * @memberof ...

Enhancing SQLite syntax in Ionic 2: A fresh approach!

Having trouble with updating my SQLite table using this script, I've edited the query but it still doesn't work. try{ this.sqlite.create({ name: 'data.db', location: 'default' }) .then((db: SQLiteObject) => ...

Leverage the Partial type within nested properties when working with TypeScript

Imagine having a type structured like this; interface State { one: string, two: { three: { four: string }, five: string } } If I were to make the state Partial, it would look like Partial<State> However, what if I specifica ...