angular 4 打字稿验证错误对象文字可能只指定已知属性

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

我的服务

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

我的模特

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

}

我的组件

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() 完美运行,但 addAccount 函数给了我

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

可能是逻辑错误,暂时不知道如何解决

您似乎忘记了使您的服务可注入(并且可能还没有在提供者列表中声明它。

问题 1 - 您没有在 AccountingComponent.

中导入 Account 界面

添加import { Account } from '../../models/Account';在你的 AccountingComponent

问题 2 - 在您的 AccountingService 中,addAccount 函数具有通用类型 <Account>,因此您还需要定义类型您从该方法返回的也是 Account 而不是默认值(即 any)。您可以通过将 res 的类型设置为 Account.

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

}