Reputation: 7
I'm trying to pass an array as an argument to a function in another component but I get this error
" Argument of type 'Item[]' is not assignable to parameter of type '[Items: Item[]]'. Target requires 1 element(s) but source may have fewer."
I look for the error and I found this (array and tuple), it seemed that it was my problem but I do not see that I have created my array that way
import { Item } from '../models/item';
import { DataService } from '../services/data.service'
export class ItemComponent {
public items: Item[] = [];
constructor(
public data: DataService,
){}
ngOnInit(): void {
this.data.addItems.apply(this, this.items) // * Here i get the error "this.items"
}
}
*I tried .apply and the spread syntax (...)
export interface Item{
id:number;
name:string;
unitPrice:number;
cost:number;
}
import {Injectable } from '@angular/core';
import { Item } from '../models/item';
@Injectable()
export class DataService{
private itemInfo: Item[];
constructor() {
this.itemInfo = [];
}
getItemInfo() {
return this.itemInfo;
}
addItems(Items: Item[]){
this.itemInfo = Items;
}
}
items in itemComponent has the value of the return of this (from other component...)
getItems(): Observable<Response>{
return this._http.get<Response>(this.url);
}
And the values on items with console.log
getItems(){
this.apiItem.getItems().subscribe( response => {
this.items = response.data;
console.log(this.items);
});
}
Upvotes: 0
Views: 679
Reputation: 2663
apply method expects its arguments in an array. So modify your this line of code
ngOnInit(): void {
this.data.addItems.apply(this, [this.items])
}
Thanks.
Upvotes: 1