[英]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 getAccounts() 工作得很好,但是 addAccount 函数给了我一个
error Object literal may only specify known properties and amount in does not exist in type Account
错误对象字面量只能指定已知的属性,并且金额在类型 Account 中不存在
it may be a logical error but I do not know how to solve it in this moment这可能是一个逻辑错误,但我现在不知道如何解决它
Problem 1 - You didn't have imported Account
interface in your AccountingComponent
.问题 1 -您没有在
AccountingComponent
导入Account
接口。
Add import { Account } from '../../models/Account';
添加
import { Account } from '../../models/Account';
in your AccountingComponent
在您的
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
).问题 2 -在您的
AccountingService
, addAccount
函数具有泛型类型<Account>
,因此您还需要将从该方法返回的类型也定义为Account
而不是默认值(即any
)。 You can solve this by setting type of the res
as Account
.您可以通过将
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.