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

Guide to displaying the continent name on a 3D globe using Reactjs, TypeScript, and Threejs

I am currently working on integrating Threejs into my Nextjs 14 application to create a 3D earth globe using Gltf. However, I am facing an issue where I am unable to display the text of the continent name on their respective continents. I want to have fixe ...

Distributing a library of components using Vite, Vue 3, and Typescript to npm

My current challenge involves publishing a Vue 3 component library with Vite, all written in Typescript. The issue I'm facing is that the type definitions are not being included in the package when imported into another project. Upon importing the co ...

Having trouble with Angular router.navigate not functioning properly with route guard while already being on a component?

I am currently troubleshooting an issue with the router.navigate(['']) code that is not redirecting the user to the login component as expected. Instead of navigating to the login component, I find myself stuck on the home component. Upon adding ...

Unable to remove loading.tsx file

Currently tackling a project using Next.js, I decided to include loading.tsx within the app directory. However, upon attempting to delete it, an error crops up: Caused by: The system cannot find the file specified. (os error 2) The import trace for the r ...

Guide to retrieving the previous URL in Angular 2 using Observables

Can someone help me retrieve my previous URL? Below is the code snippet I am working with: prev2() { Promise.resolve(this.router.events.filter(event => event instanceof NavigationEnd)). then(function(v){ console.log('Previous ' ...

Discover the solution to the issue of bookmarking a card on a page using react, typescript, and mui!

Whenever I try to favorite a card by clicking on its icon, all cards of the same type get bookmarked instead of just the one I clicked on. This is causing an issue where multiple cards are being favorited per page when I only want to bookmark individual on ...

How to correct placeholder text display in the input of a Material UI text field

Currently, I am utilizing the material ui text field component. The issue at hand is that when the text field is in focus, the placeholder shifts to the top of the field. https://i.stack.imgur.com/P5flf.png I prefer for the placeholder to remain within ...

Verify the data types of components received as props in a Typescript React application

I have a question regarding type checking in React components passed as props: What is the method for ensuring that only allowed components are passed as props? Allow me to demonstrate. We have the component we wish to pass around: type CustomProps = { ...

Authenticate using oidc-client-js and automatically redirect to a different web application

Having some trouble with the authentication process. I'm not entirely convinced it's well thought out. https://i.stack.imgur.com/62ju6.png I've got an Angular app specifically for user login and registration. When a user wants to log in 1, ...

Changing the background color of .pane and .view elements in an Ionic web application using JavaScript

Looking to modify the background-color of two css selectors, .pane and .view, that are located within the ionic.css file. Despite multiple attempts to do so using JavaScript directly in the index.html file, the changes are not reflected. The code snippet ...

Displaying Image Preview in Angular 2 After Uploading to Firebase Storage

At the moment, I am facing an issue where the uploaded image is not being displayed after the uploadTask is successful. This problem arises due to the asynchronous loading nature of the process, causing the view to attempt to display the image before the u ...

Struggling to store information in a MongoDB database within my MEAN Stack project

After successfully creating a collection for user LOGIN/LOGOUT and managing to store and retrieve data using Express app and mongoose, I encountered an issue when trying to create another collection. Despite successfully creating the collection, the data w ...

What causes type checks to be skipped when spreads are used on type-guarded types?

Query: Why doesn't a compile-time error occur when I overlook adding nested fields to an object of type T, while constructing the object using object spread? Illustration: interface User { userId: number; profile: { username: string } } f ...

A guide on displaying an Angular Component within a Thymeleaf page

Currently, I am faced with the task of integrating Angular and Thymeleaf. This is necessary because I have developed a dynamic graph using Angular and now need to incorporate it into an existing project that utilizes Thymeleaf. Are there any simplified m ...

Troubleshooting: Issues with APIGateway's Default Integration

I'm currently utilizing the AWS CDK to construct my API Gateway REST API My objective is to have my RestApi configured to automatically return an HTTP 404 error, so I set it up as follows: this.gateway = new apigw.RestApi(this, "Gateway", { ...

Issue with mediaelement in Angular 8: video playback does not display after 2 seconds

I'm encountering an issue with MediaElement js when trying to play videos in .m3u8 format within a slider containing multiple videos. Whenever I click on the play button for any video, only a 2-second clip is shown before the video disappears. Any as ...

Grid layout with columns of equal width in Bootstrap

I'm currently working on creating a dashboard with Angular and Bootstrap 4. I've utilized the equal-width columns from https://getbootstrap.com/docs/4.0/layout/grid and it's functioning well. However, I'm facing an issue where if the lo ...

Utilizing Angular2 Observables for Time Interval Tracking

I'm working on a function that needs to be triggered every 500ms. My current approach in angular2 involves using intervals and observables. Here's the code snippet I've implemented so far: counter() { return Observable.create(observer =&g ...

Struggling with importing aliases in TypeScript for shadcn-ui library

I am facing a challenge with resolving TypeScript path aliases in my project. I have set up the tsconfig.json file to include path aliases using the "baseUrl" and "paths" configurations, but alias imports are not functioning as intended. My goal is to imp ...

Angular 4 - Issues with route configurations

My Angular application is running smoothly on localhost:4200 using ng serve. The node server can be found at localhost:3000. After running ng build, a bundle file is generated and properly served from localhost:3000 thanks to the line app.use(express.sta ...