Pablo
Pablo

Reputation: 7

trying to pass an array as an argument

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);
    });
  }

itemsValues on the console

Upvotes: 0

Views: 679

Answers (1)

Mujadid Mughal
Mujadid Mughal

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

Related Questions