Angular is throwing an error stating that the type '{ }[]' cannot be assigned to the type '[{ }]'

I'm in need of assistance and clarification regarding the error I encountered in my application... When I receive a JSON response from an API with some data that includes an array of products, I aim to extract these products (izdelki) from the array, store them in a new empty array, and send them back to the backend via another API call. However, I'm facing difficulties in retrieving the products from the received array. Here's the error message my code is throwing:

error TS2322: Type '{ sifra: string; naziv: string; kolicina: number; ean: string; em: string; cena: number; rabat1: number; rabat2: number; prednarocilo: number; ismail: number; }[]' is not assignable to type '[{ sifra: string; naziv: string; kolicina: number; ean: string; em: string; cena: number; rabat1: number; rabat2: number; prednarocilo: number; ismail: number; }]'.
[ng]   Target requires 1 element(s) but source may have fewer.
[ng] 
[ng] 38         this.orderProducts = data.map(this.order['izdelki']);

I'm still getting familiar with Angular and handling Arrays seems to be a bit challenging for me :)

Here is the code snippet for single-order.ts:

export interface SingleOrder {
  id: number;
  datum: string;
  datum_dobave: string;
  dostava: number;
  g_popust: number;
  opomba: string;
  predkoci1narocilo: number;
  kc: number;
  prevoznik: string;
  narocilnica: string;
  narocilnicadate: string;
  izdelki: {
    sifra: string;
    naziv: string;
    kolicina: number;
    ean: string;
    em: string;
    cena: number;
    rabat1: number;
    rabat2: number;
    prednarocilo: number;
    ismail: number;
  }[];
}

This is the service code used to retrieve the single order:

getSingleOrder(id: number): Observable<SingleOrder[]> {
    return from(Preferences.get({ key: 'TOKEN_KEY' })).pipe(
      switchMap(token => {
        const headers = new HttpHeaders().set('Authorization', `Bearer ${token.value}`);
        return this.httpClient.get<SingleOrder[]>(`${environment.apiUrl}customer/orders/${id}`, { headers, observe: 'response' });
      }),
      catchError(err => {
        console.log(err.status);
        if (err.status === 400) {
          console.log(err.error.message);
        }
        if (err.status === 401) {
          this.authService.logout();
          this.router.navigateByUrl('/login', { replaceUrl: true });
        }
        return EMPTY;
      }),
      map(res => res.body)
    );
 };

Below is the code snippet for order-view.page.ts:

export class Izdelki {
  sifra: string;
  naziv: string;
  kolicina: number;
  ean: string;
  em: string;
  cena: number;
  rabat1: number;
  rabat2: number;
  prednarocilo: number;
  ismail: number;
}
@Component({
  selector: 'app-order-view',
  templateUrl: './order-view.page.html',
  styleUrls: ['./order-view.page.scss'],
})
export class OrderViewPage implements OnInit, OnDestroy {
  order: SingleOrder[];
  // orderProducts: SingleOrder['izdelki'][];
  orderProducts: SingleOrder['izdelki'][];
  repeatOrderArr: Izdelki[];
  private orderSubscription: Subscription;
  constructor(
    private route: ActivatedRoute,
    private customerService: CustomerService,
  ) { }

  ngOnInit() {
    this.getOrder();
  }

  getOrder() {
    const id = Number(this.route.snapshot.paramMap.get('id'));
    this.orderSubscription = this.customerService.getSingleOrder(id).subscribe(
      data => {
        this.order = data;
        console.log('Order data:', this.order);
        this.orderProducts = data.map(this.order['izdelki']);

      },
      error => {
        console.log('Error', error);
      });
  }

  repeatThisPurchase() {
    this.repeatOrderArr= [...this.orderProducts];
    console.log(this.repeatOrderArr);
  }

  ngOnDestroy(): void{
    this.orderSubscription.unsubscribe();
  }

}

To provide further insight into the JSON response structure, here's a screenshot of the console.log(data): https://i.sstatic.net/rNpcC.png

The following snippet shows the HTML file code:

<ion-button color="vigros" class="purchase-btn" size="default" type="submit" (click)="repeatThisPurchase()" expand="block">Ponovi nakup</ion-button>

Answer №1

Imagine if we consider "izdelki" as a category

export class Izdelki {
      sifra: string;
      naziv: string;
      kolicina: number;
      ean: string;
      em: string;
      cena: number;
      rabat1: number;
      rabat2: number;
      prednarocilo: number;
      ismail: number;
    }

In the SingleOrder interface, you assigned an array of type [Izdelki] to izdelki

export interface SingleOrder {
  izdelki: [Izdelki]
}

However, in your subscription code, you treated it as if izdelki is of type Izdelki directly

This caused the SingleOrder's izdelki to change to

export interface SingleOrder {
  izdelki: Izdelki
}

Alternatively, if izdelki is supposed to be an array

 export interface SingleOrder {
      izdelki: Izdelki[]
    }

To resolve this issue, you must:

  1. Specify izdelki in SingleOrder as type Izdelki
  2. Declare orderProducts as an array consisting of SingleOrder['izdelki']

orderProducts: SingleOrder['izdelki'][];

Answer №2

You should always start by declaring the type of the array before adding any elements to it. For example, in TypeScript you can declare an array interface like this:

export interface SingleOrder {
...
items: {
      code: string;
      name: string;
      quantity: number;
      ean: string;
      em: string;
      price: number;
      discount1: number;
      discount2: number;
      backorder: number;
      ismail: number;
    }[];
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing a react element to fail to update?

I'm currently working on a React component that interacts with a MaterialUi text form. The component utilizes a useState hook to update based on the input received. My goal is to have another variable update when the form is submitted, which will be d ...

"Troubleshooting issues with Material Design components in AngularJS: Why is <md-select> not functioning correctly

I'm attempting to implement the <md-select> tag, but I can't seem to achieve the same result as shown here. This is the code I've written: <div layout="column" layout-align="center center" style="margin: 0px 10px 0px 5px;"> & ...

Adding JSON data to an array in Node.JS

I am facing an issue where my JSON data is successfully being appended to an array inside a JSON file. However, the problem is that it is not appending inside of the brackets in the JSON file. Below is the code snippet for my NODE if (req.method == &apo ...

My project encountered an error when trying to serve with Angular-cli (property 'slice' of null cannot be read)

Everything was running smoothly with my project until now, but after making some modifications to a node_modules file, I encountered an issue. Whenever I attempt to use the "ng" command, I receive the following error message: /usr/lib/node_modules/angula ...

Issue encountered with ngFor: 'Identifier not defined __type does not have any such member'

Recently, I successfully implemented a sub-component that allows users to dynamically add and remove a set of controls to and from a collection. The inspiration for this solution came from reading through this particular thread on Stack Overflow. While ev ...

How can we effectively share code between server-side and client-side in Isomorphic ReactJS applications?

For a small test, I am using express.js and react.js. Below you can find my react code: views/Todo.jsx, var React = require('react'); var TodoApp = React.createClass({ getInitialState: function() { return { counter: 0 ...

Utilizing Backward and Forward Navigation with AJAX, JavaScript, and Window.History

TARGET Implement Ajax for fetching pages Utilize JavaScript to update the window URL Leverage Window History to preserve Ajax page for seamless forward-backward navigation without reloading the page Modify the Navigation bar's attributes (such as co ...

Does Javacc have a capability to generate JavaScript code as an output?

Is there a parser generator available that can take a Javacc grammar file (.jj) and produce a JavaScript parser instead of Java? If not, what would be involved in converting the .jj file into a format that ANTLR can interpret (since it has the capability ...

CSS Challenge: How to crop an image without using its parent container directly

I'm currently facing a complex CSS challenge that I can't seem to solve. I want to create an image controller (two-by-two layout on two lines) that can display: The top-left image in full size, The top-right with horizontal scrolling, The botto ...

Having trouble with passing the callback for nested mysql queries in Async.waterfall?

I am facing an issue with my nested MySQL queries where async.waterfall is not working as expected. The second step of the waterfall is failing to append its result to the array: async.waterfall([ function(callback) { connection.query(query, function( ...

What is the best way to store values in a map for future reference within a Kotlin class?

Looking to implement a map of key value pairs in Kotlin inside a class that is mutable and can be updated and referenced as needed. Research suggests that using a MutableMap would be the appropriate choice, given its ability to be updated at any point. I ...

Encountered an error while running npm run dev on a NextJS application due to an

Upon running the npm run dev command, the next app is displaying an error message: $→mmoLD;%g?wŷ↓▬ovH0a5*ؒl͛Siy☺rO7%L]%∟hk ^ SyntaxError: Invalid or unexpected token at wrapSafe (internal/modules/cjs/loader.js:988:16) at Module._comp ...

Error occurs when attempting to clear the cache storage

useEffect(async () => { caches.open('my-cache') }, [token, user_id]) Upon trying to log out of the application, const logoutFunc = () => { localStorage.clear() caches.keys().then((list) => list.map((key) => { ...

Nest is unable to resolve DataSource in the dependency injection

I've encountered an issue with dependencies while working on my NestJS project. When I try to launch the app, the compiler throws this error at me: [Nest] 16004 - 09.04.2022, 16:14:46 ERROR [ExceptionHandler] Nest can't resolve dependencies of ...

Submitting a form via NextJS to an internal API

After reading through the Next.JS documentation, I came across an interesting point. Note: Instead of using fetch() to call an API route in getStaticProps, it's recommended to directly import the logic from within your API route and make necessary cod ...

Using TypeScript to handle text resolution through the command line interface

Currently, I am developing a CLI application using TypeScript and employing enquirer for the purpose. More information about enquirer can be found here. In my project, I have a JSON object defined as follows: const person = { name: 'Mohan', ...

How to Stop AJAX Requests Mid-Flight with JQuery's .ajax?

Similar Question: Stopping Ajax Requests in JavaScript with jQuery Below is the straightforward piece of code that I am currently using: $("#friend_search").keyup(function() { if($(this).val().length > 0) { obtainFriendlist($(this).va ...

Difficulty encountered when assigning object properties as callback results in node-tesseract package

I'm attempting to utilize the outcomes of a callback function as properties of an object. Here is an example of how I am implementing the module I am constructing: var Capture = require("./Capture.js") const example = async function() { let scr ...

Angular 5 and the world of HTTP connections

As I embark on my journey of creating my very first Angular 5 application, one of the key components is its interaction with the Java Rest Web Services that I have developed using Spring Boot. The foundation of this integration lies in the following RESTfu ...

Titanium: Picture -> "automatically"

Imagine there is an image named hello.png with the dimensions of 200x100. A button is then created using this hello.png as shown below: var btn = Titanium.UI.createButton({ bottom : 50, backgroundImage : "images/hello.png", width:100, height:"auto"; }); w ...