繁体   English   中英

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

[英]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 函数给了我一个

错误对象字面量只能指定已知的属性,并且金额在类型 Account 中不存在

这可能是一个逻辑错误,但我现在不知道如何解决它

问题 1 -您没有在AccountingComponent导入Account接口。

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

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

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

}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM