Search code examples
angulartypescriptangular4-httpclient

angular 4 typescript validation error Object literal may only specify known properties


my 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);
  }
}

my model

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

}

my 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() works perfectly but addAccount function give me a

error Object literal may only specify known properties and amount in does not exist in type Account

it may be a logical error but I do not know how to solve it in this moment


Solution

  • Problem 1 - You didn't have imported Account interface in your AccountingComponent.

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

    Problem 2 - In your AccountingService the addAccount function have generic type <Account>, so you need to also define the type that you are returning from that method also as Account and not the default (which is any). You can solve this by setting type of the res as Account.

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

    }