Using Angular, a class can serve as a method within another class

I am new to Angular2 and encountering a problem. I have developed a component called info. In the info.component.ts file, I am initializing objects in the following way:

import { Comm } from '../shared/comments';
...
const VASACOM: Comm = {
  name: 'Vasa',
  id: 122,
  comments: [
    {
     rating: 5,
     comment: "Some commment",
     date: "2012-10-16T17:57:28.556094Z"
    },
   {
    rating: 4,
    comment: "Other comment",
    date: "2014-09-05T17:57:28.556094Z"
   }
  ]
};

The class Comm in comments.ts:

export class Comm {
 name: string;
 id: number;
 comments: Comment[];
 constructor(name:string,id:number,comments:Comment[]){
   this.name = name;
   this.id = id;
   this.comments = comments;
 }
}

export class Comment {
   rating: number;
   comment: string;
   date: string;
}

However, I encounter an error:

error TS2322: Object literal may only specify know properties, and 'comments' does not exist in type 'Comm'

Can you point out what mistake I made?

p.s. I am aware that we can create 2 separate objects, one using the Comm class and the other with Comment, but I prefer keeping them in a single object.

Answer №1

When creating instances of your Comm and Comments classes, utilize their constructors.

export class Comm {
  constructor(
    public title: string,
    public postID: number,
    public feedback: Feedback[]
  ){}
}

export class Feedback {
   constructor(
     public rating: number,
     public opinion: string,
     public timestamp: string
   ){}
}

Answer №2

Have you considered rebooting the server? It could potentially resolve the issue at hand.

Answer №3

one way to organize those classes is by using an interface

export interface CommData {
 name: string;
 id: number;
 comments: CommentData[];
}

export interface CommentData {
   rating: number;
   comment: string;
   date: string;
}

to easily access the data, you can utilize a service like this:

@Injectable()
export class ItemService {
  getAllItems(): CommData[] {
    return VASACOMMENTS;
  }

the structure of the data should resemble this example:

const VASACOMMENTS: CommData[] = [{
  name: 'Vasa',
  id: 122,
  comments: [
    {
     rating: 5,
     comment: "Some commment",
     date: "2012-10-16T17:57:28.556094Z"
    },
   {
    rating: 4,
    comment: "Other comment",
    date: "2014-09-05T17:57:28.556094Z"
   }
  ]
}];

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

The Angular4 Grunt build task is encountering an issue where it cannot locate the module '@angular/core/testing'

I've been working on setting up a Grunt build task for my Angular 4 project, but I'm encountering some module load errors when trying to run the tasks. Here are the steps I have taken so far: 1. Visited https://angular.io/guide/quickstart and f ...

Using the Bootstrap link transforms my nav bar into a structured table design

I'm encountering an issue with my navigation bar: When I include the stylesheet link from Bootstrap <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH ...

Make simultaneous edits to multiple cells in IGX GRID for Angular

Is it feasible to edit multiple cells in the same column simultaneously within igx grid Angular? I would like for the changes made within each cell to be displayed at the same time. Editing many cells all at once is a valuable feature! ...

Troubleshooting Guide for Resolving the Issue: Module "@angular/core/src/view/util" Not Found

As I work on my final year project with Ionic, my laptop unexpectedly experienced a short circuit. Now, I am continuing the development of my project using multiple computers and laptops, but I'm facing an issue where my project's output is not d ...

Encountered an error while trying to access a property that is undefined - attempting to call

In my TypeScript class, I have a method that retrieves a list of organizations and their roles. The method looks like this: getOrgList(oo: fhir.Organization) { var olist: orgRoles[] = []; var filtered = oo.extension.filter(this.getRoleExt); f ...

How come the index variable doesn't show the index in *ngFor loop in Angular 2?

When working with ng-repeat in Angular 1 to display the index, this code is used: <div ng-repeat="car in cars"> <ul> <li>Index: {{$index+1}}</li> <li>Car Name:{{car.name}}</li> </ul> </div> However, w ...

Is there a way to carry out tests on keydown events within Jasmine by specifying the keyCode within an Angular2+

I am working on a project where I need to trigger keydown events on an <input> field. Tools Used Karma v1.7.1 as the test runner Tests running on Chrome browser Using Angular 5 framework Any insights on how I can achieve this? ...

Leveraging constructors for injecting dependencies in Angular is a key practice for enhancing modularity and maintainability

After reviewing the Angular Official documents and various blogs, I noticed that there are two different syntaxes for Dependency Injection (DI) when used within the constructor. Sometimes this is utilized, while other times it is not. This leads to the que ...

Animated drop-down menu in Angular 4

I recently came across this design on web.whatsapp.com https://i.stack.imgur.com/ZnhtR.png Are there any Angular packages available to achieve a dropdown menu with the same appearance? If not, how can I create it using CSS? ...

What is the best way to locate an item within a Redux array when working with TypeScript?

Below is the content of my slice.ts file. interface iItem { Category: string; Id: string; } interface iDataState { Items: Array<iItem>; } const initialState: iDataState = { Items: [], }; reducers: { updateItem: (state, action: PayloadAc ...

Data shared among various RXJS Observables

I am currently in the process of refactoring some code to utilize RXJS and the angular async pipe. The task at hand involves adding and removing items from an array. I'm wondering if there might be a more efficient approach to manipulating a shared ar ...

Error message: In my router module, Angular's 'Subject' is not subscribed to

Currently, I am utilizing a canActivateFn guard in my application where I am subscribing to a Subject. This particular Subject was instantiated in a separate service, and I'm perplexed as to why the subscription does not seem to trigger (the callback ...

How can I pass custom QueryParams to Router's NavigationExtras in Angular and create a personalized navigation experience?

I am currently working on implementing data filtering functionality in my Angular application. The concept is fairly simple - the user selects filters from dropdown menus and then clicks a button to add key-value pairs of filters to the URL route. There a ...

What's the Advantage of Using a Getter for a Public Field in Angular?

Having come from a background in Java where the practice is to make variables as private as possible, I've noticed in Angular that private fields are not used frequently. What is the reasoning behind not making fields private if it's possible? ...

The datepicker in Angular 2 is not displayed properly in Firefox when using the input with the type=date attribute

Everything is functioning properly in the Chrome browser. <div class="form-group"> <label for="date">Date:</label> <input class="form-control " [(ngModel)]="journal.record.date" type="date" required/> </div> <br/& ...

Leverage Sinon's fakeServer in combination with promises and mocha for efficient

Having an issue here: I need to test a method that involves uploading data to an AWS S3 bucket. However, I don't want the hassle of actually uploading data each time I run my tests or dealing with credentials in the environment settings. That's w ...

Exploring the process of defining methods within a child Vue component

componentA.vue: <script lang="ts"> import { Vue } from 'vue-property-decorator' @Component export default class ComponentA extends Vue { public methodA(): void { // } } </script> componentB.vue: <template> ...

The icon for caret down in FontAwesome is not displaying when using ngClass

I am experiencing an issue where only the fontawesome caret up is displayed when sorting a field, but the fontawesome caret down is not showing. I have provided the code snippet below. HTML <th (click)="sort('ref')">Ref {{reverse}} & ...

Viewing the photo container before uploading while having text overlap

I'm encountering an issue where the image previews are overlapping with the text in another div. Here are the screenshots: the first one shows how it looks before the preview, and the second one shows what happens when images are added: https://i.sst ...

Tips for transferring an excel file to a C# controller from Angular 4 within Visual Studio 2017

I'm working on a web application where I need to import an Excel file and send it to the server-side controller. On the server-side, I am utilizing EPPlus for this task. Can anyone provide guidance on how to accomplish this? I would greatly appreci ...