【发布时间】: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 -
github.com/michelnovellino/angular-crudgithub上的仓库
标签: angular typescript angular4-httpclient