Data not being retrieved by HTTP GET request

I encountered an issue with my API where I made three Get requests using the same function but different URLs to differentiate between them. However, even though the provider returns the data in steps, the page response function does not receive it and shows either null or "Unexpected end of JSON".

Page Code:

loadNature() {
    this.expenseProvider.fetchDropdown('http://xx.xx.xx.xx:xxxx/api/v1/cadastros/natureza/get-dropdownlist/002/001')
    .then((arr_proj) => {

        this.obj_data = arr_proj;

        this.nature_list = [];
        for (let i = 0; i < this.nature_list.length; i++) {
            this.obj += (
                this.nature_list[i]
            )
            this.nature_list.push(this.obj);
        }
    })
}

Provider code:

fetchDropdown(url: string) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json; charset=UTF-8');
    headers.append('Authorization', 'bearer ' + this.global.tokenGlobal);
    let options = new RequestOptions({ headers: headers });

    return this.http.get(url, options)
      .toPromise()
      .then(response => {
          var json_data = (response as any)._body;
          var parsed = JSON.parse(json_data);

          var arr_data = [];

          for (var x in parsed) {
              arr_data.push(parsed[x]);
          }

          return arr_data;
      })
      .catch((error) => {
          var json_error = (error as any)._body;
          var parsed = JSON.parse(json_error);

          var arr = [];

          for (var x in parsed) {
              arr.push(parsed[x]);
          }

          return arr[0];
      });
  }

Answer №1

It appears that you may be encountering an issue with the following line of code. I recommend starting by adding a console.log(arr_proj) to troubleshoot.

this.obj_data = arr_proj; // Initializing response object here
this.lista_natureza = []; // Creating an empty array

for (let i = 0; i < this.lista_natureza.length; i++) {
    // Checking the length of an empty array will prevent execution, as there are no elements present
    this.obj += (
        this.lista_natureza[i]
    ) // Rewriting your intended logic implementation 
    this.lista_natureza.push(this.obj);
}

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

What is the best way to implement Infinite scroll alongside Virtual scroll in Ionic 3?

Having recently delved into the world of Ionic and Angular, I am encountering some difficulties with implementing Infinite scroll alongside Virtual scroll. Despite pushing data such as images, text, and click functions from TypeScript, only empty Ionic car ...

Creating nested return types: A guide to defining function return types within a Typescript class

My large classes contain functions that return complex objects which I am looking to refactor. class BigClass { ... getReferenceInfo(word: string): { isInReferenceList:boolean, referenceLabels:string[] } { ... } } I am considering somethi ...

What triggers the execution of the catch method while chaining HTTP promises?

In my Angular application, I have developed a custom loaderService that displays a loading spinner while the back-end processes requests. Below is the code snippet: export class ComponentOne { constructor(loaderService: LoaderService, orderService: Orde ...

Why is the table not sorting when I apply filters?

I am encountering an issue where the data filters and table sorting are not working together. When I apply filters, the sorting functionality stops working. The filters work fine independently, but once applied, they interfere with the sorting feature. Any ...

How to invoke a method in a nested Angular 2 component

Previous solutions to my issue are outdated. I have a header component import { Component, OnInit } from '@angular/core'; import { Router, NavigationEnd } from '@angular/router'; import { Observable } from 'rxjs/Observable'; ...

Ways to check my component using ActivatedRoute?

I am currently facing an issue while testing a component that utilizes two resolvers (pagesResolver and UploadResolver): Below is the code snippet for my component: export class AdminPagesComponent implements OnInit { fileUploads$: Observable<FileUpl ...

The assigned type 'string' for Apache ECharts does not match the expected type 'pictorialBar'

This demonstration is functional. Nevertheless, the options utilize any and my goal is to convert them to the EChartOption type. This is my current progress and the demonstration compiles successfully with this setup (With type: 'bar' commented ...

The value of 'Boolean' cannot be changed as it is a constant or a read-only property and cannot be assigned

I've been working on creating a TypeScript object to handle read/write permissions in my application, but I'm stuck on an issue with variable assignment that doesn't make sense to me. Any help or guidance would be greatly appreciated. expor ...

Switching positions in Azure DevOps (Angular + API): How can the Angular configuration be modified for the designated slot?

Setting up the Angular app can be quite tricky. In our Azure Yaml pipeline publishing job, we tackle the challenge by executing a "token" replacement to tailor the configuration for the specific target environment within a tokenized artifact. Subsequently ...

Format Currency Fields with Comma Separated Values in Angular and Material UI

In our Angular 9 project, we are implementing currency input fields that require a standard masked label displaying a comma separated format. When the user enters 56000.55 into the input field, upon blur event, we need to show 56,000.55 as a comma separat ...

What are some ways to enhance Rxjs syntax?

save(): void { combineLatest(this.selectedSorting$, this.selectedFilters$) .pipe( map((data) => { let obj = {}; if (data[0]) { obj['fil ...

Leveraging prop data to create dynamic router links in Vue

I am attempting to develop a feature that will dynamically update links on ion buttons depending on the props received. So far, I have: <template> <ion-button router-link :to "`$/+ {{subLink1}}" shape="round">{{linkName1}}& ...

Error: The method that was custom created is not functioning as expected

I am working on a project where I have a collection of hero buttons that come with a customized animation which is defined in the button.component.ts file. These buttons start off as inactive, but when one is clicked, it should become active. To achieve th ...

Optimal scenarios for implementing computed/observables in mobx

I understand most of mobx, but I have a question regarding my store setup. In my store, I have an array of objects as observables using TypeScript: class ClientStore { constructor() { this.loadClients(); } @observable private _clients ...

Determine rest parameters based on the initial argument

Struggling to generate a solution that infers the arguments for an ErrorMessage based on the provided code input. ./errorCodes.ts export enum ErrorCodes { ErrorCode1, ErrorCode2, ErrorCode3 } ./errorMessages.ts export const ErrorMessages = { [Err ...

Pass data between different parts of the system

Utilizing the angular material paginator has been a great experience for me. You can check it out here: https://material.angular.io/components/paginator/examples. The paginator triggers an event which allows me to print the page size and page index. This f ...

The type definition file for '@wdio/globals/types' is nowhere to be found

I'm currently utilizing the webdriverio mocha framework with typescript. @wdio/cli": "^7.25.0" NodeJs v16.13.2 NPM V8.1.2 Encountering the following error in tsconfig.json JSON schema for the TypeScript compiler's configuration fi ...

Issue encountered in Angular app-routing module.ts: Type error TS2322: The type '"enabled"' cannot be assigned to type 'InitialNavigation | undefined'

When I recently updated my project from Angular 11 to 14, I encountered the following error when running "ng serve". Error: src/app/app-routing.module.ts:107:7 - error TS2322: Type '"enabled"' is not assignable to type 'InitialNavigation | u ...

The identifier "id" is not a valid index for this type

The code snippet below demonstrates the similarities and differences between the functions addThingExample2 and addThing. While addThingExample2 directly uses the union type Things, addThing utilizes a generic parameter THING extends Thing. The expression ...

Using the css function within styled-components

Struggling with implementing the media templates example from the documentation and figuring out how to type the arguments for the css function in plain JS: const sizes = { desktop: 992 } const media = Object.keys(sizes).reduce((acc, label) => { ...