Unexpected error: Angular 4 TypeScript validation issue - An object literal can only define recognized properties

excellent customer service

import {Account} from '../models/Account';

  export class AccountingService {
  domain: string = "http://localhost:3000/api";

  constructor(private http: HttpClient) {  }

  getAccounts(){
    return  this.http.get<Account[]>(`${this.domain}/accounts` )
              .map(res => res)
  }

  addAccount(newAccount:Account){
    return  this.http.post(`${this.domain}/accounts`,newAccount)
              .map(res=>res);
  }

  updateAccount(newAccount: Account){
    return this.http.put(`${this.domain}/accounts/${newAccount.id}`,newAccount)
              .map(res=>res);
  }

  deleteAccount(id){
    return  this.http.delete(`${this.domain}/accounts/${id}`)
              .map(res=>res);
  }
}

customer account model

export class Account{
    _id?: string;
    name: string;
    amount: number;

}

service component

import {AccountingService} from '../../services/accounting.service';

@Component({
  selector: 'app-accounting',
  templateUrl: './accounting.component.html',
  styleUrls: ['./accounting.component.css']
})
export class AccountingComponent implements OnInit {
  accounts:Account[];
  name:string;
  amount:number;
  constructor(private accountService : AccountingService ) {

    this.accountService.getAccounts()
      .subscribe(accounts =>{
        console.log(accounts);
      })

   }

   addAccount(event){
    event.preventDefault();
    const newAccount : Account={
      name: this.name,
      amount: this.amount
    };

    this.accountService.addAccount(newAccount);
   }

getAccounts() is performing well, however, the addAccount function is presenting me with a

issue: Object literal may only specify known properties and 'amount' does not exist in type Account

It could be a logical mistake, but I am unsure how to resolve it at this moment

Answer №1

Issue 1 - The Account interface was not imported in the AccountingComponent.

Add

import { Account } from '../../models/Account';
to your AccountingComponent

Issue 2 - In the AccountingService, the addAccount function has a generic type of <Account>. You also need to specify the type that is being returned from that method as Account and not the default (any). This can be resolved by setting the type of res as Account.

addAccount<Account>(newAccount: Account) {
    return this.http.post(`${this.domain}/accounts`, newAccount)
       .map((res: Account) => res);

}

Answer №2

Looks like you may have overlooked making your service Injectable and possibly forgot to include it in the provider list.

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

Steps to activate Angular Progressive Web App service worker

When I set up an Angular project, I executed the following commands in the terminal: ng add @angular/pwa ng build --prod The static website output was published in the /dist folder. After running the URL through PWABuilder, it detected the manifest bu ...

Spring MVC seems to be ignoring the static resources specified in the HTML files

Currently, I am in the process of creating a straightforward Spring MVC (v4.1.2) and Angular4 application. Essentially, this application performs CRUD operations by sending HTTP requests from the Angular client. The following combination works seamlessly ...

Erase Mistake in Pop-up Angular JSON Information and Bootstrap

Encountering an ERROR TypeError: Cannot read property 'id' of undefined while attempting to delete data in a modal using Bootstrap. When I click the button, I correctly receive the data in JSON format in the modal (as shown in the image). Any ide ...

Issue encountered in Ionic/React/Typescript - Incorrect props supplied to React.FC<'erroneous props provided here'>

Having struggled with this issue for a while now without any success, I have searched through numerous questions here but none seem to address my specific case. Therefore, I kindly request your assistance. I am encountering difficulties passing props thro ...

Encountering the error message "Received 1 argument, when expecting 4" while attempting to utilize a vuex getter in TypeScript

I encountered an issue while unit testing a getter function. The error message Expected 4 arguments, but got 1. appeared when I attempted to use the getter. My application was built using Quasar and utilizes TypeScript. The value of HttpMocks.mockToken is ...

Utilizing arrayUnion function in Firestore with Angular

My journey to learn Firestore has hit a roadblock. The documentation on AngularFire and FieldValue hasn't been much help. Every time I try to use FieldValue, it throws an error saying "FieldValue does not exist." const userRef = this.firestore.collect ...

The onChange event will not be triggered in an input component that is not intended to be uncontrolled

Could someone please assist me in understanding why the onChange event is not being triggered? I am customizing ChakraUI's Input component to retrieve a value from localStorage if it exists. The component successfully retrieves the value from localS ...

Managing the token prior to the page loading: best practices

Implementing JWT for authentication without a login page has posed some challenges for me. The issue arises when the site loads and immediately starts with the GET methods to load content before authenticating and saving the token in local storage. The pr ...

Using TypeScript to pass an object's method as an argument in a function call

Recently, I delved into game development using cocos creator with TypeScript/JavaScript, languages that are still new to me. My current challenge involves creating a complex callback method that will trigger methods attached to an array of objects. Here&a ...

Creating a custom Higher Order Component to seamlessly connect react-relay and react-router using TypeScript

Hey there! So, my Frankenstein monster project has decided to go rogue and I'm running out of hair to pull out. Any help would be greatly appreciated. I've been working on setting up a simple app with React, React-Router, React-Relay, and Typesc ...

How can you assign a strokeStyle color to a Canvas using a CSS property?

Our team is currently working on an Angular2 / Ionic 2 project where we have implemented a HTML Canvas element that allows users to draw on it. One challenge we are facing is how to set the Canvas strokeStyle property using a color provided by a CSS style. ...

What is the best way to transfer the current index of a component that is nested within another component?

Seeking guidance on implementing a unique feature for my Hero Component, which includes a background image and a carousel. My goal is to dynamically change the background images based on the current slide visible in the carousel. However, I am facing a cha ...

Creating a sequence of dependent HTTP requests in Angular

Is it possible to execute multiple http get requests sequentially in Angular, where the endpoint URL for the second request depends on the response of the first request? I attempted to nest the requests using the following code snippet: this.http.get(end ...

Develop a personalized React route component using TypeScript. The error message "Property 'path' does not exist on type... RouteProps" is displayed

I am currently working on creating my own route component using React. Although I am new to TypeScript, I believe that is the root cause of the issue I am facing. import * as React from 'react' import { ApplicationState } from '../../store& ...

Ways to customize the OverridableComponent interface within Material-UI

Is there a way to effectively use the Container component with styled-components incorporating ContainerProps, while still being able to pass the component prop that belongs to the OverridableComponent interface? Currently, I am encountering an error when ...

The Angular CLI suddenly decided to stop providing me with useful lines (without sourcemaps) in the browser console, but interestingly the terminal continues

I recently noticed a change in my Angular project that is using Angular CLI. Instead of receiving error lines from my code, I am getting errors from compiled files like main.js and vendor.js. The 'normal' error messages in my terminal are pointin ...

How can we recreate this ngModel text input form in a radio format for a spring boot mvc and angular application?

As I was following a tutorial on creating an employee CRUD model using spring boot and mysql server for the backend and angular for the frontend, I encountered a form group during the creation process. The tutorial originally had a text input field for gen ...

How to implement ngx-spinner in an Angular http subscribe operation

I'm trying to incorporate a spinner into my Angular Application using ngx-spinner. I've come across this library but haven't found enough practical examples on how to use it effectively. Specifically, I want to integrate the spinner with my ...

It appears that Typescript mistakenly interprets a class or type as a value, indicating that "'Classname' is being referred to as a value but used as a type here."

I want to pass an Object of a React.Component as "this" to a Child React.Component in the following way: component 1 file: class Comp1 extends React.Component<...,...> { ... render() { return (<Comp2 comp1={this}/> ...

What is the best way to call a method within a TypeScript class using its name as a string while already inside the class itself?

Currently, I am developing a class that automates the creation of routes for Express and invokes a function in a controller. However, upon trying to execute this[methodName](req, res), I come across an error message stating: 'Element implicitly has an ...