What could be the reason behind TS showing the error "Type 'MyMedicine[]' cannot be assigned to type 'MyMedicine' as a parameter"?

Here is an interface I have created:

export interface MyMedicine {
  _id: String;
  name: String;
  quantity: Number;
  time: String;

}

This snippet shows my Angular service used for posting data:

postMed(newMed): Observable<MyMedicine[]>{
  var headers = new HttpHeaders();
  headers.append('Content-Type', 'application/json');
  return this.http.post<MyMedicine[]>(`${this.url}/api/medicine`, newMed, {headers:headers});

}

The following code block demonstrates a component function addmedicine() that posts data upon form submission:

addmedicine(){
  const newMedicine = {
    name: this.name,
    quantity: this.quantity,
    time: this.time
  };
  this.medService.postMed(newMedicine)
      .subscribe(medicine =>{
        this.medicines.push(medicine);
      })}

An error message is displayed stating: "Argument of type 'MyMedicine[]' is not assignable to parameter of type 'MyMedicine'. Type 'MyMedicine[]' is missing the following properties from type 'MyMedicine': _id, name, quantity, time"

The necessary imports of the interface and service have been included in the component. Dependency injection has been properly managed. Note that _id corresponds to the default id generated by MongoDB.

Answer №1

Just to recap, the issue lies in the fact that you are getting an array of MyMedicine from this.medService.postMed.

An effective solution could be to only include the last element received from the array.

medicines: MyMedicines[];

this.medService.postMed(newMedicine).subscribe(medicines => this.medicines.push(medicines.pop()))

Answer №2

To ensure that the HTTP post request only returns the newly added item to the MyMedicines[] array, make adjustments to the postMed method as shown below:

postMed(newMed): Observable<MyMedicine>{
var headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
return this.http.post<MyMedicine>(`${this.url}/api/medicine`, newMed, {headers:headers});

In the component class, consume the observable emitted by the HTTP post request in the following manner:

addmedicine(){
const newMedicine = {
  name: this.name,
  quantity: this.quantity,
  time: this.time
};
this.medService.postMed(newMedicine)
    .subscribe((medicine : MyMedicine) =>{
      this.medicines.push(medicine);
    })}

Kindly verify from your end if the solution is functioning correctly.

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

Tips on adding TypeScript annotations to an already existing global function

I'm contemplating enhancing an existing project by incorporating TypeScript type annotations. Struggling to supply an external declaration file for a straightforward example: app.ts: /// <reference path="types.d.ts"/> function welcome (person ...

The Angular frontend application with proxy configuration is sending requests to the incorrect backend URL

My application is using Angular 11.0.6 as the front end, deployed on IIS and configured for mywebsite.com (port 80). The backend consists of a dotnet core web API deployed on IIS and configured for my.server.ip.address:190. Both the front end and back end ...

Does the TS keyof typeof <Object> rule prohibit the assignment of object.keys(<Object>)?

I'm having trouble understanding the issue with this code snippet. Here is the piece of code in question: export type SportsTypes = keyof typeof SportsIcons export const sports: SportsTypes[] = Object.keys(SportsIcons); The problem arises when I at ...

Encountering difficulties importing a component from a library into my Nx Expo React Native application

Having an issue with my Nx monorepo which contains an Expo React Native app and various libraries. The problem arises when trying to import a component from a library within the application, resulting in Error: Cannot resolve @monorepo/account-manager Wi ...

Is there a way for me to view the output of my TypeScript code in an HTML document?

This is my HTML *all the code has been modified <div class="testCenter"> <h1>{{changed()}}</h1> </div> This is my .ts code I am unsure about the functionality of the changed() function import { Component, OnInit } f ...

Discover the step-by-step guide to setting up forwarding in React Router 5

Just diving into the world of React and TypeScript. I'm working with a component called Err. Is there a way to redirect it using React Router 5? import React, { FC, Fragment, useEffect } from "react"; const Err: FC<{ error: string }> = ({ erro ...

Issue with migrating from Angular version 2.4.10 to 4.0.0

After attempting to update my application from Angular 2.4.10 to 4.0.0, I used the following command: "npm install @angular/common@next @angular/compiler@next @angular/compiler-cli@next @angular/core@next @angular/forms@next @angular/http@next @angular/pl ...

"What is the appropriate TypeScript type for this specific JSX code - React.ReactElement, React.ReactNode, and React.FunctionComponent all prove to be inadequate in this

Having an issue with assigning a type to my prop SubmissionComponent. This prop is expecting JSX, possibly a button or a more complex structure. For example: const SubmissionComponent = <p>hi</p>; which is then used like this: <Submitter ...

Tips on incorporating dynamic expressions within ngFor loops?

Is there a way to dynamically display specific properties from objects in an array (list: any[]) within an *ngFor loop in Angular? I am currently working on a component called ListComponent that is responsible for rendering a list of items. The parent com ...

Vue - Troubleshooting why components are not re-rendering after data updates with a method

Check out this simple vue component I created: <template> <div class="incrementor"> <p v-text="counter"></p> <button v-on:click="increment()">Increment</button> </div> </template> <script lan ...

Error: Unable to access properties of null (specifically 'writeValue')

My goal is to retrieve an object by its ID, and if the object does not exist, the component will then register the object. However, when the object does exist, it retrieves the object normally, but then throws the same error again. HTML: <div class="c ...

Angular - utilizing subscription within a for-loop to determine completion

Below is the code I am using to generate sticky notes: update() { this.tab3Service.updateStickyNote(this.stickyNoteUserConnection.stickyNote).subscribe(response => { const updatedStickyNote: StickyNote = response; for(let i = 0; i < this.stickyNo ...

Verifying Whether Objects in TypeScript File Adhere to a Certain Interface

Currently, I am in the process of developing a procedure that scans through a collection of *.ts files within a directory to identify those containing a class that implements a specific interface. While my preference is to be able to detect multiple classe ...

Exploring the method to retrieve data on the server side through Express when it is shared by the client within a put request

Here is the angular http put request I am working with: sendPutRequest(data) : Observable<any>{ return this.http.put("http://localhost:5050", data).pipe(map(this.handleData)); } After making this call, the server side method being invoked is ...

Can you explain the mechanics behind Angular Component CSS encapsulation?

Is it possible to avoid CSS conflicts when using multiple style sheets? Consider Style 1: .heading { color: green; } And Style 2: .heading { color: blue; } If these two styles are applied in different views and rendered on a layout as a Partial Vi ...

Enhancing React TypeScript: Accurate typings for Route's location and children attributes

I am facing an issue with my router as it passes props of location and children, but I am uncertain about the correct types for these props. Here is the code snippet for the router using react-router-dom... import React, { useReducer } from 'react&a ...

How can I arrange a table in Angular by the value of a specific cell?

Here's the current layout of my table: Status Draft Pending Complete I'm looking for a way to sort these rows based on their values. The code snippet I've been using only allows sorting by clicking on the status header: onCh ...

Develop a FormGroup through the implementation of a reusable component structure

I am in need of creating multiple FormGroups with the same definition. To achieve this, I have set up a constant variable with the following structure: export const predefinedFormGroup = { 'field1': new FormControl(null, [Validators.required]) ...

Footer missing from Tanstack React table

Library Version: "@tanstack/react-table": "^8.2.6", I have been attempting to include footers in my table without success. Despite setting static footer text with a fixed value, I am unable to render any dynamic values similar to how h ...

Adding an element to an array does not automatically reflect on the user interface

After fetching JSON data from the endpoint, I am attempting to update an array but not seeing the expected results on the frontend. export class LocationSectionComponent implements OnInit{ myControl = new FormControl(); options : string[] = [' ...