【问题标题】:angular 4 typescript validation error Object literal may only specify known propertiesangular 4 typescript验证错误对象文字只能指定已知属性
【发布时间】:2019-05-14 23:11:10
【问题描述】:

我的服务

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类型中不存在金额

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

【问题讨论】:

  • 这看起来像代码应该可以正常工作没有任何错误:你能提供 Stackblitz 例子吗?还要检查您是否没有输错任何属性:) 也不要导出 class Account 尝试导出 interface Account

标签: angular typescript angular4-httpclient


【解决方案1】:

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

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

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

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

}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-06
      • 2015-10-27
      • 2019-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多