Angular displays [object Object] upon return

I have been struggling to send a post request, but unfortunately the API is returning undefined. When I try to send it to my API, it shows up as [object Object]

getAccouting():Observable<any>{
    // let json = this.http.get<any>('/assets/cities/altayskiy_kray/accounting.json'); if i use it json return undefined
    let json;
    this.http.get('/assets/cities/altayskiy_kray/accounting.json').pipe(data=>json=data);
    let formData:FormData = new FormData;
    formData.append('json', json);
    return this.http.post<any>('http://api/api.php', formData);
  }

Does anyone know how to fix this issue?

Answer №1

When using asynchronous functions like <code>http.get
, it's important to consider the order in which they will be executed. In this case, if you try to access the response before returning the http.post, the variable json will likely be undefined.

To ensure proper execution, you can chain these functions together and return the complete observable:

getAccouting(): Observable<any>{
  return this.http.get('/assets/cities/altayskiy_kray/accounting.json').pipe(
    switchMap(json => {
      return this.http.post<any>('http://api/api.php', json);
    }
  );
}

If you need to use FormData, appending the json object may result in its string value being displayed as [object Object].

To avoid this issue, you can stringify the json object before appending it, but remember that it will need to be decoded on the server side:

formData.append('json', JSON.stringify(json))

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

Displaying buttons based on the existence of a token in Angular - A guide

Can you assist me with a coding issue I'm facing? I have implemented three methods: login, logout, and isAuthenticated. My goal is to securely store the token in localStorage upon login, and display only the Logout button when authenticated. However, ...

What is the process for sending a post request in Ionic 2 to a Node server running on localhost?

When working with Ionic, I utilized a service provider to access HTTP resources. The Service.ts file looks something like this. Here, data is represented as a JSON object. import { Injectable } from '@angular/core'; import { Http, Headers } fro ...

npm error: JSON input unexpectedly ended while parsing

Encountered an error when running ng new project-name in my Angular project. npm WARN deprecated [email protected]: CircularJSON is in maintenance only, flatted is its successor. npm ERR! Unexpected end of JSON input while parsing near '...: ...

What could be causing the global npm package to not be utilized for module dependencies?

My typescript and ts-node are already installed globally. In my package.json file, I have the necessary configurations to run tests with npm test. Everything works fine since ts-node and typescript are installed as local modules. { "name": "two_sum", ...

What is causing the subscriber to receive the error message "Cannot access 'variable' before initialization" while referencing itself?

Within my Angular 8 project, I have a component that is dependent on a service for data loading. It waits for a notification from the service signaling that it has finished loading in the following manner: constructor(public contentService: ContractServic ...

Simulating TypeDI service behavior in Jest

My current setup includes Node with TypeScript, TypeDI and Jest. I've been working on creating services that have dependencies on each other. For example: @Service() export class MainService{ constructor(private secondService: SecondService){} public ...

Typescript: When using ts-node-dev, an error occurred while trying to import express due to an unexpected

I am embarking on a fresh project using Typescript and I intend to set up the node server with typescript utilizing express. There's a helpful tutorial that explains how to execute a Typescript file without going through the hassle of compiling files, ...

Utilizing Observable for Navbar concealment in Angular 2

Here's my dilemma: I have a navbar in my app.component that I want to hide before someone logs in by setting a boolean variable to true using ngIf. app.component.html: <navbar *ngIf="_userLoggedIn === true" ></navbar> <router-outlet& ...

Tips for adjusting the position of nodes that are overlapping in React Flow

Whenever node1 is moved over node2 in react-flow, they end up overlapping. I am looking to shift node2 towards the right to avoid this overlap. The desired outcome is for node2 to be shifted to the right side. ...

What are some methods for retrieving RTK Query data beyond the confines of a component?

In my React Typescript app using RTK Query, I am working on implementing custom selectors. However, I need to fetch data from another endpoint to achieve this: store.dispatch(userApiSlice.endpoints.check.initiate(undefined)) const data = userApiSlice.endpo ...

Guide to dynamically including a tooltip in an input box using Angular 2

I need to implement a feature where a Tooltip message is displayed when hovering over an input box. The content of the Tooltip message will depend on the response received from a service. If the service responds with 'true', the Tooltip message s ...

Fake AxiosInstance. In need of obtaining response in a single test

In my api.ts file import axios from 'axios' export const api = axios.create({ baseURL: 'http://localhost:3333/', }) Within my react-page.spec.tsx file: import React from 'react' import '@testing-library/jest-dom&apo ...

Error: The specified module 'tty' was not found in the directory '/workspace/node_modules/pace/node_modules/charm'

My attempt to compile my frontend project using ng build resulted in the following error message: ERROR in ./node_modules/pace/node_modules/charm/index.js Module not found: Error: Can't resolve 'tty' in '/workspace/node_modules/p ...

Tips for specifying the return type of app.mount()

Can I specify the return value type of app.mount()? I have a component and I want to create Multiple application instances. However, when I try to use the return value of mount() to update variables associated with the component, TypeScript shows an error ...

Determine the specific cell involved in an HTML5 drag-and-drop interaction within a table

I've been experimenting with the HTML5 drag and drop functionality in an Angular project. Here's the setup I'm working with: A container containing draggable 'objects' A table where users can drop the dragged elements Following ...

The value of Angular Input remains unchanged within a FormArray

I am experiencing an issue with the Sequence No in my PreprocessingForm's FormArray. When I add a new row, the Sequence No does not change as expected. <tr class="mat-row" *ngFor="let dynamic of PreprocessingForm.controls.arithmeticI ...

Passing a React functional component with SVG properties to another component as a prop

My goal is to import a React functionComponent from an SVG and pass it as a prop to another component for rendering the svg. The code below compiles without errors, but crashes when trying to display the svg in the browser with the following message: Er ...

Tips for simulating a service in Angular unit tests?

My current service subscription is making a promise: getTaskData = async() { line 1 let response = this.getTaskSV.getTaskData().toPromise(); line 2 this.loading = false; } I attempted the following approach: it('should load getTaskData', ...

Interactive Angular Interfaces Featuring Numerous Numeric Choices Within the Main Object

I am currently in the process of designing an interface for my Angular project that allows users to search for video games using the WhatToPlay API within RapidAPI. When a user searches for details on a video game, the result will return a game identified ...

Is it possible for me to exclude generic parameters when they can be inferred from another source?

Imagine having a scenario like this: type RecordsObject<T, K extends keyof T> = { primaryKey: K; data: Array<T>; } where the type K is always derived from the type T. Oftentimes, when I try to declare something as of type RecordsObject, ...