I'm curious as to why I am receiving an empty array as a response when I send a post request to the API

I am experiencing an issue while sending data to an API using a post method. I have structured the data in an object as per the server's requirements, but upon posting the object to the API, I receive a response with a status of 200 and an empty array. Is the response supposed to be similar to the "Response samples" shown in the print screen?

The service where the post request is made:

  voteGame(vote:vote) {
    const body = vote;
    return this.http.post<vote>('https://api-labs.tindin.com.br/games/rate', body).subscribe(data => console.log(data));
  }

The model created for the object is as follows:

  export interface vote {
    gameId: string;
    rate: number;
  }

The function that triggers the service call:

  voteGame(vote: number) {
    const voteObj = {
      gameId: this.gameId,
      rate: vote,
    };
    console.log(voteObj);
    this.voteGameService.voteGame(voteObj);
  }

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

Answer №1

If I understand correctly, you are looking to fetch a response from a REST endpoint and incorporate it into your application.

Firstly, you can define a type for the response of the REST endpoint:

export type VoteGameResponse {
  game: string;
  totalVotes: number;
  ...   
}

Next, the method for posting a new vote should simply return an Observable from the HttpClient:

export class VoteGameService { 
  voteGame(vote: Vote): Observable<VoteGameResponse> {
    return this.http.post<Vote>('...', vote);
  }
}

Then, the application can request a new vote by subscribing to the observable and using the response to update the view, for example:

voteGame(vote: number) {
    this.voteGameService.voteGame({
      gameId: this.gameId,
      rate: vote,
    }).subscribe(response => {
      this.totalVotes = response.totalVotes;
      //... or any other updates to the view
    })
}

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

Having trouble adding Bootstrap to Angular with Webpack? You might come across the error message: "File to import not found or unreadable: ../bootstrap/sc

I have decided to incorporate Bootstrap into my project. My attempt at installation involved using "bootstrap": "^4.0.0-alpha.5" I followed a tutorial found at https://github.com/AngularClass/angular2-webpack-starter/wiki/How-to-use-Bootstrap-4-and-Sass- ...

How to Retrieve Grandparent Component Attributes in Angular Using Grandchild Components

I am constructing an Angular application and facing the challenge of accessing a property of Component 1 within Component 3. In this scenario, the relationship is described as grandparent-grandchild. Successfully establishing communication between parent/ ...

Is there a way to create a new perspective for Ion-Popover?

Looking for a solution: <ion-grid *ngIf="headerService.showSearch()"> <ion-row id="searchbar" class="main-searchbar ion-align-items-center"> <ion-col size="11"> ...

Issue of displaying buttons based on sibling's height under certain conditions

OBJECTIVE I have undertaken a project to enhance my skills in React and TypeScript by developing a UI chat interface. The design requirement is that when a chat message has enough vertical space, its action buttons should appear stacked vertically to the ...

Identifying changes in a property's value binding within Angular 4

One way to detect changes in a property decorated with @Input is by implementing the OnChanges interface: export class EmployeeComponent implements OnChanges { @Input() message: string; startDate: Date; ngOnChanges(changes: SimpleChanges) { fo ...

Issue with data propagation in Angular 2 RC5 when using ngStyle in parent component

Here is a basic Angular 2 application setup I am working with: import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>Test</h1> <test-component [Height] = "30 ...

Steps for including a component in a loop using Angular 6

I'm working on a component that contains two input fields. The goal is to have a row pop up every time the user clicks on the add button, with all the inputs eventually being collected in an array of objects. For example, the component template looks ...

Guidelines for accessing a specific object or index from a dropdown list filled with objects stored in an array

Here is a question for beginners. Please be kind. I have created a select field in an HTML component using Angular, populated from an array of objects. My goal is to retrieve the selection using a method. However, I am facing an issue where I cannot use ...

Tips for creating the perfect ngrx state structure

Currently, I am working on adding a new feature state that includes a graph state with two subfeatures: node state and link state. Here is how I have implemented the graph state and reducer: export interface GraphState { [fromNode.featureKey]: fromNode ...

Can you tell me how to add a custom CSS class to a cell in ag-grid using Angular?

I am facing a challenge with applying CSS to cells in ag-grid in Angular based on specific logic. I have assigned an object to the grid, where one of the fields contains a value for Object.hours and I need to apply styling based on the Object.status proper ...

The attribute 'subtle' is not found within the definition of 'webcrypto' type

Currently, I am working with Node v17.4 and I am looking to utilize the webcrypto API. Referencing this specific example, I am attempting to include subtle in my project, but TypeScript is throwing an error: Property 'subtle' does not exist on ...

Creating subclass mappings and defining subclasses dynamically using Typescript at runtime

I am puzzled by the structure of 3 classes: A, B, and C. Both B and C extend the abstract class A. abstract class A { public name: string; constructor(name: string) { this.name = name; } abstract getName(): string; } class B extends A { g ...

What is the best way to store user data from an Angular App into the Firebase Realtime database?

As I delve into the world of Angular by following a tutorial, I find myself struggling with saving users to the Firebase database. Despite successfully logging in, the database remains empty. import { Injectable } from '@angular/core&apo ...

Stop images from constantly refreshing upon each change of state - React

Within my component, I have incorporated an image in the following way: <div className="margin-10 flex-row-center"> <span> <img src={spinner} className="spinner" /> ...

Angular 6 offers a dynamic auto complete feature that enhances user

My Angular app has auto-complete functionality enabled. I am using ngFor to iterate over an array of objects and passing the index of the object array to a function for some operations. Below is the code snippet I have tried: template.html <mat-form ...

Resizing svg to accommodate a circle shape

As I work on my vue.js app that involves a plethora of diverse icons, I made the decision to create a small icons builder in node.js. The purpose is to standardize their usage and also "crop" each SVG so it fits perfectly within its parent container by uti ...

Tips for organizing your CSS from scratch without relying on a pre-existing framework such as bootstrap, bulma, or materialize

As I embark on a new Angular project, the decision has been made to create our own component library instead of using frameworks like Bootstrap, Bulma, or Materialize. Despite some initial research, I'm feeling a bit lost on where to begin (other than ...

Can someone explain how to create a Function type in Typescript that enforces specific parameters?

Encountering an issue with combineReducers not being strict enough raises uncertainty about how to approach it: interface Action { type: any; } type Reducer<S> = (state: S, action: Action) => S; const reducer: Reducer<string> = (state: ...

What is the best way to display individual records from a Web API on the user interface?

Just a heads up: I'm unable to utilize pagination (skip, take) due to the data being sourced from multiple tables. For more information, you can refer to the Report model. I attempted to retrieve the data individually on the UI through WebAPI. The ...

When it comes to rendering components in React using multiple ternary `if-else` statements, the question arises: How can I properly "end" or "close" the ternary statement?

I have developed a straightforward component that displays a colored tag on my HTML: import React, {Component} from 'react'; import "./styles.scss"; interface ColorTagProps { tagType?: string; tagText?: string; } /** * Rende ...