Error Alert: missing property data in angular 5 type

I attempted to design an interface in interface.ts. The data consists of an array of objects inside the Column. Below is the code for my interface:

export class User {
result: boolean;
messages: string;
Column=[];
data=[];
}
export class Column {  
name:string;
category:boolean;
count:number;
}

export class data {
name:string;
category:string;
}

The following code is used in the service.

getData(): Promise<User> {
return Promise.resolve(
{ result: true, messages: 'Maria','Column':[{
name:'ramu',category:'c',count:4, "data":[{"name":"",      "category:""
    }]
}]
}
);
}

However, I encountered a type error. I have attached a screenshot below for your reference. Please check and see the error screenshot. Code URL Stackblitz

https://i.stack.imgur.com/KASbQ.png

Answer №1

Give it a shot

  fetchData(): Promise<Person> {
return Promise.resolve(
{ success: true, note: 'Maria',
  'Columns':[{   person:'John',gender:'male',age:30}], 
 "details":[{ "name":"", "occupation":"" }]
});
}

Answer №2

Check out the code snippet below.

import { Injectable } from '@angular/core';
import { Http, Headers, Response, URLSearchParams, RequestOptions } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { User } from './interface';
import { Column } from './interface';

import 'rxjs/add/operator/map';

@Injectable()
export class DataService {

  userCookie: any;
  loginAlertMessage: string;
  constructor(private http: Http
  ) {
  }

  getData(): Promise<User> {
    return Promise.resolve(
      {
        result: true, messages: 'Maria',
        'Column': [{ name: 'ramu', category: 'c', count: 4 }],
        "data": [{ "name": "", "category": "" }]
      });
  }
}

DEMO

Answer №3

Explore the interface.ts

export class User {
  isValid: boolean;
  feedback: string;
  Column=[];
}
export class Column {  
  title:string;
  isCategory:boolean;
  total:number;
  rows=[]; 
}
export class RowData {
  title:string;
  category:string;
}

Data Service Operation

getData(): Promise<User> {
    return Promise.resolve(this.data);
}

DEMO IN ACTION

Answer №4

Some may argue that the suggestions offered by other responses are valid.

However, in my personal view, it is recommended to utilize "type assertion" to specify the object as the Type you need (assuming the data aligns with the required format)...

getData(): Promise<User> {
    return Promise.resolve(
      {
        result: true, messages: 'Maria',
        'Column': [{ name: 'ramu', category: 'c', count: 4 }],
        "data": [{ "name": "", "category": "" }]
      } as User);
  }

In essence, append as User at the end of the object.

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

Utilizing NPM Workspace Project in conjunction with Vite to eliminate the necessity of the dist folder during the Vite build process

I am currently working on a project that involves a module using full path exports instead of index files. This project is divided into 2 NPM workspaces: one called core and the other called examples. The challenge I am facing is avoiding long import pat ...

Guide to accessing a nested and potentially optional object property with a default value and specifying its data type

Just a simple query here... my goal is to extract data.user.roles, but there's a possibility that data may be empty. In such cases, I want an empty array as the output. Additionally, I need to specify the type of user - which in this instance is any. ...

What could be causing the inner array typescript to be inaccessible in an Angular 5 application?

Below are the JSON definitions that I am working with: export class Company { name: string; trips : Trip[] = []; } export class Trip{ id: number; name: string; } Within the component, there is a method that contains the ...

Incorporate TypeScript with Angular 2 to construct a dictionary with <key, value> pairs. Then, utilize a JSON file to populate the dictionary with data

I am in need of assistance with creating a dictionary or list with a specific structure. I have prepared a json file within my angular 2 project, and I would like to load this data into the dictionary that I am creating. Sample content from my Json file: ...

Using Angular's asyncValidator in conjunction with BehaviorSubject allows for real

Currently, I am working on developing an Angular form. Below is a snippet of my code where I am attempting to construct a multi-group form with an async validator. The scenario involves validating whether a number exists in a specific list. In a real-worl ...

Issue: Keeping the mat-form-field element in a single line

I am facing an issue with incorporating multiple filters for each column in an angular material table. I cannot figure out why the filter input is not moving to a new line under the header. Here is an image for reference -> Angular material table with m ...

Is it possible to construct an Angular project without altering the file size limit?

The budget of 40.00 kB fell short by 60.66 kB for a total of 80.66 kB. I've been grappling with the issue of exceeding the max file limit for anyComponentStyle. While working with Material UI and utilizing indigo-pink.css in my component scss, I&apo ...

A function that has a declared type other than 'void' or 'any' is required to return a value

I'm facing an issue in my angular2 application where a service is sending a get request to a specific URL. Below is the code snippet of the service: import {Http} from '@angular/http'; import {Observable} from 'rxjs/Observable'; i ...

Issues Arise with Nativescript Layout When Content is Not in View on iOS

This problem has been giving me a hard time for the past few days. I hope someone can help me figure out what's wrong. I have a view that shows a nested list inside a main list. The main list contains header details. Everything looks fine when the in ...

What is the most graceful method to define a class attribute just once?

Is there a clean and efficient way to set a value only once within a TypeScript class? In other words, is there a way to make a value read-only after it has been assigned? For instance: class FooExample { public fixedValue: string; public setFixe ...

Creating a customizable table in Angular with resizable columns that can retain their width and size preferences

I'm in the process of creating an Angular application that allows users to add or remove columns based on their preference and priority. My goal is to design a table with resizable column widths and save the adjusted column width in local storage so ...

Firebase Angular encountering issues with AngularFirestoreModule

I have encountered a challenge with Firebase authentication in my Angular applications. Due to updated read and write rules that require auth!=null, I successfully implemented Firebase authentication in one of my apps using Angular 13. Now, I am trying to ...

Using Angular 2 to efficiently recycle a subcomponent with the same form across multiple parent components while maintaining its state

I've been struggling to find someone with the same issue as me, even though the title may seem familiar. Perhaps I need help rephrasing my question? Here's an explanation: Use case: I have multiple routes (only 2 in the example below) set up fo ...

Place the Div in a consistent position on images of varying widths

I have a dilemma with my class that is supposed to display images. The issue arises when I try to place a div within an image inside this class. Everything works smoothly when the image takes up the entire width of the class, but as soon as the image widt ...

I'm struggling to make basic CSS work in my Next.js 13 project. I'm a beginner, can someone please help?

I am facing issues with the default CSS in my latest project. I have a file called page.modules.css and I am using classname = styles.style page.tsx import styles from'./page.module.css' export default function Home() { return ( <div cl ...

Every time I clear the information, it seems to be instantly replaced with new data. How can I prevent it from constantly refilling?

When I press the remove button on my application, it successfully deletes the data in a field. However, it also automatically adds new data to the field which was not intended. I am seeking assistance on how to keep those fields empty after removing the ...

What are some ways to resolve this console error: "TS2307: Could not locate module '@components/common/ButtonBlock' or its corresponding type declarations."

While the project is running smoothly, I am noticing a multitude of errors appearing in the console of VS Code. How can I eliminate these error messages? It seems to be related to TypeScript. Additionally, I am encountering an error in the browser as well ...

Utilizing a variable to pass props to a component (instead of a static component) within React Router 5

In react-router 5, you can pass props to a child component in this way: <Route path="/" exact render={ props => <MyPage title={myTitle} dataPath={myDataPath} {...props} />} /> However, I am using a route model in my ...

Library of Functions in Angular 2

As I develop my application, I'm considering creating a functions library that can be utilized by various components. What would be the most effective approach to achieve this? Should I create a service containing all the functions, or rely on classes ...

Simulating a PubSub publish functionality

I have been trying to follow the instructions provided in this guide on mocking new Function() with Jest to mock PubSub, but unfortunately I am facing some issues. jest.mock('@google-cloud/pubsub', () => jest.fn()) ... const topic = jest.fn( ...