In Angular 5, you cannot assign type 'any[]' to type 'typeof User'

After extracting data from the JSON file, I encountered a typo error message stating: Type 'any[]' is not assignable to type 'typeof User'. Here is my code in app.component.ts:

import { Component, OnInit } from '@angular/core';
import { User, UserService } from './user.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [UserService]
})
export class AppComponent implements OnInit {
title = 'Users list';
usersdata:User;
constructor(private userService: UserService) { }
ngOnInit(){
this.userService.getUsers().then(users => this.usersdata = users.data);
}
}
and here is the code in user.service.ts:

import { Injectable } from '@angular/core';
export class User {
id: number;
name: string;
data=[];
}
export class data {
name:string;
category:string;
}
@Injectable()
export class UserService {
constructor() { }
getUsers(): Promise<User> {
return Promise.resolve(
{ id: 1, name: 'Maria','data':[{
name:'ramu',category:'c' 
}]});
}
}

You can see my complete code at this URL Code URL Stackblitz

I have attached a screenshot of the typo error below. Can you please help me identify where I made a mistake?https://i.sstatic.net/c5qqn.png

Answer №1

Make sure to include a User type like this:

return Promise.resolve<User>(
{ id: 1, name: 'Maria','data':[{
name:'ramu',category:'c' 
}]}
);

Additionally, update the data type in the component to any[]

usersdata:any[];

Answer №2

Check out the code snippet below to see an example.

import { Component, OnInit } from '@angular/core';
import { User, UserService,data } from './user.service';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],

}) 
export class AppComponent implements OnInit {
  title = 'Users list';

  usersdata: Array<data>;
  constructor(private userService: UserService) { }
  ngOnInit() {
    this.userService.getUsers().then(users => this.usersdata = users.data);

  }
}

DEMO

Answer №3

Within the User class, you have defined the property data as an array by initializing it as [].

However, in your AppComponent, you are attempting to assign a value of type User to user.data, which is of type any[]. This mismatch causes a TypeScript error.

To resolve this issue, make sure that you are using the correct types throughout your code.

Option A: Assign the entire User object to userdata.

usersdata: User;

ngOnInit() {
    this.userService.getUsers().then(users => this.usersdata = users);
}

Option B: Adjust the type of userdata to match the type of User.data.

usersdata: any[];

ngOnInit() {
    this.userService.getUsers().then(users => this.usersdata = users.data);
}

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

Alert message will be displayed upon clicking on stepper titles in Angular 10

I need to implement an alert when the user clicks on the second stepper labeled 'Fill out your address'. In addition to displaying a red border around the empty form field, I also want to show an alert message. I have already set up a function ca ...

The Angular logout route appears to be neglected

I'm currently working on implementing a LogoutFunction, but I'm running into an issue where it's not being dispatched to my API (Spring Boot). The login functionality works perfectly fine. My goal is to pass an ID to the API and receive a su ...

A guide to showcasing data within PrimeNG's pie chart component using either JavaScript or Angular

I have utilized the pie chart feature from the PRIMENG CHART PLUGIN My goal is to showcase the values within a pie chart Below, you can find my code for reference **Within app.component.html** <div style="display: block"> <p-chart type="pi ...

How to Implement Multi Select Drag and Drop Feature in Angular 4?

Currently, I am implementing Angular 2 Drag-and-Drop from this library to enable the selection of list items using a drag and drop method. However, I have encountered issues with its functionality on touch devices and when attempting to perform multiple it ...

How to customize toggle icon in Angular Material mat-slide-toggle

I'm currently using Angular6 to design my user interface. The default style of the mat-slide-toggle button is shown below: https://i.stack.imgur.com/tIqus.png However, I would like the toggle button to have the appearance of the material-icons togg ...

The callback function does not seem to work when using MUI v4 PropFunc

Encountering an issue with custom styling using PropFunc in Material UI (MUI) v4 (4.12.4). When providing a PropFunc in the traditional callback way to get CSS, it works as expected: const useStyles = makeStyles((theme) => { return { input: { ...

Is there a way to optimize Typescript compiler to avoid checking full classes and improve performance?

After experiencing slow Typescript compilation times, I decided to utilize generateTrace from https://github.com/microsoft/TypeScript/pull/40063 The trace revealed that a significant amount of time was spent comparing intricate classes with their subclass ...

Problem with the Auto-fill Feature in PrimeNG Module

Check out my code on Gist:   https://gist.github.com/rickymuvel/8ddc4d14d90877329447ddde9c0aa835 The issue I'm facing involves the Autocomplete module in PrimeNG. It seems that the specific path in the ubigeo.service.ts file is not being called. Her ...

Modify the dynamic style of an Angular input field

Looking for assistance with a text box <input type="text" [ngStyle]="(show_div===true) ? {'border-color':'red','color':'red'} : {'border-color': 'green','color':'g ...

What is the best way to make an attribute in an interface mandatory only when another attribute is set to true

How can a relative be made required only when another attribute is true? For Example: interface ITesteProps { required: boolean content{!required && '?'}: string } I understand that this code is not valid. Is it possible to make the ...

Transform a list of H1..6 into a hierarchical structure

I have a task to convert H1 to H6 tags from a markdown file into a JavaScript hierarchy for use in a Table of Contents. The current list is generated by AstroJS and follows this format [{depth: 1, text: 'I am a H1'}, {depth: 2: 'I am a H2}] ...

Using Angular 2 with the @ngtools/webpack for Ahead of Time (AOT)

I'm attempting to implement AOT in Angular 2 using webpack and @ngtools/webpack. During compilation, I encounter no errors. However, upon opening the site in the browser, a console error occurs: No NgModule metadata found for 'AppModule' ...

Why am I not achieving the desired code coverage in Jest while testing Angular?

I've recently developed a small project to monitor coverage results, but I'm encountering some unexpected issues. It seems like there's a configuration mistake on my end, but I'm struggling to identify what adjustments need to be made t ...

JavaScript Equivalent to C#'s BinaryReader.ReadString() Function

Currently, I am in the process of translating C# code into JavaScript. While transferring multiple datatypes from this file to matching functionalities found in various JavaScript libraries was relatively smooth, there is one specific function that seems t ...

Essential typing techniques required for manipulating data retrieved from GraphQL

My headless CMS is responsible for generating all types in my GraphQL schema. Upon querying, I receive a result that contains an array which I can manipulate. However, when attempting to use filter, map, or find methods on the returned array, an error me ...

Creating separate template reference variables for items in an *ngFor loop in Angular can be achieved by using the

I have a question about setting template reference variables for buttons with different attributes when rendering them using *ngFor in Angular. Specifically, I want to set the reference variable as #button1, #button2, and so on for each button, but also ne ...

Is it possible to utilize a variable for binding, incorporate it in a condition, and then return the variable, all while

There are times when I bind a variable, use it to check a condition, and then return it based on the result. const val = getAttribute(svgEl, "fill"); if (val) { return convertColorToTgml(val); } const ancestorVal = svgAncestorValue(svgEl, "fill"); if (a ...

How to Utilize an Array from Observable Object in Angular 2 with ngFor and Async Pipe

I am currently learning about the utilization of Observables in Angular 2. Here is a snippet of code from a service I am working with: import {Injectable, EventEmitter, ViewChild} from '@angular/core'; import {Observable} from "rxjs/Observab ...

Inject Angular 2 component into designated space

I am working on a website that requires a settings dialog to be loaded in a designated area upon clicking a button. The settings dialog is a component that retrieves data from REST endpoints. I am hesitant to simply insert the component and hide it as I ...

Do not display large numbers within an HTML card

I have https://i.sstatic.net/DkowD.png this card here and displaying dynamic data inside it. The number is quite large, so I would like it to appear as 0.600000+. If a user hovers over the number, a tooltip should display the full number. How can I achieve ...