угловая ошибка проверки машинописи 4 Литерал объекта может указывать только известные свойства - PullRequest
0 голосов
/ 13 декабря 2018

мой сервис

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 Литерал объекта может указывать только известные свойства, а сумма не существует в типе Account

это может быть логической ошибкой, но я новичок и не знаю, какчтобы решить это, помогите мне :(

Ответы [ 2 ]

0 голосов
/ 14 декабря 2018

Проблема 1 - Вы не импортировали Account интерфейс в свой AccountingComponent.

Добавьте 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);

}

0 голосов
/ 13 декабря 2018

Похоже, вы забыли сделать свой сервис инъекционным (и, возможно, еще не объявили его в списке провайдеров.

...