Home > OS >  Property 'commentText' does not exist on type 'Comment'
Property 'commentText' does not exist on type 'Comment'

Time:03-09

I'm building a simple social network application with Angular 12 (for my own learning). I'm getting an error at the moment I was wondering if you can help.

Firstly about the App:

  • On the first page (home.component.html) there is a list of user profiles.
  • On clicking a list item (user profile) a userID is passed as a parameter to the ProfileComponent.
  • The ProfileComponent displays an individual user profile (along with a list of posts created by that user (similar to facebook)).
  • With this userID (that was passed in to the profile component), I call a method from my post.service which makes an API call to retrieve an observable with an array of Posts.

Note: Each Post object has a property called comments which is (should be) an array of Comment objects (defined in comment.model.ts).

The Post data is displaying well in my profile template however when I try to display properties of the comments array I get the error:

Property 'commentText' does not exist on type 'Comment'

However, If I change the comments property (in the post.model.ts) to have a type of any then there is no error and the comments are displayed properly. However I would like to do it in right way so i'd appreciate your help/advice.

I'm new to this environment so please excuse if the error is something simple. Thanks for your help.

Here is my code:

I created two models for the posts section (so far): Comment and Post.

comment.model.ts

export class Comment {
  commentID?: number;
  commentUserID?: number;
  commentText?: string;
  commentTime?: string;
  postID?: number;
}

post.model.ts

export class Post {
  postID?: number;
  postUserID?: number;
  postText?: string;
  postTime?: string;
  photoLink?: string;
  postType?: string;
  videoLink?: string;
  isYoutubeVideo?: boolean;
  youtubeVideoCode?: string;
  youtubeEmbedLink?: any;
  comments?: Comment[]; //If I change this to any; then i don't get an error in the template
}

profile.component.ts

import { Component, OnInit } from '@angular/core';
import { UserService } from '../user.service';
import { PostService } from '../post.service';
import { ActivatedRoute, Router } from '@angular/router';
import { User } from '../user.model';
import { Comment } from '../comment.model';
import { Post } from '../post.model';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
  currentUser: User = {
    userID: 1,
    firstName: "",
    lastName: "",
    username: "",
    profileImgUrl: "",
    bio: "",
    emailAddress: ""
  };
  posts?: Post[];

  constructor(private userService: UserService,
    private postService: PostService,
    private route: ActivatedRoute,
    private router: Router) { 
  }

  ngOnInit(): void {
    const routeParams = this.route.snapshot.paramMap;
    const userIDFromRoute = Number(routeParams.get('userID')); //cast it to a Number
    console.log(userIDFromRoute); //log the userID to make sure it is correct
    this.getCurrentUser(userIDFromRoute);
    this.getPosts(userIDFromRoute);
  }

  getPosts(userID: number): void {
    //call the getPosts(userID) method from the post service in order to retrieve
    //an array of "Post" objects for this particular user.
    //Each "Post" object will contain an array of "Comment" objects
    this.postService.getPosts(userID)
      .subscribe(
        data => {
          this.posts = data;
          console.log(data);
        },
        error => {
          console.log(error);
        });
  }
}

post.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Comment } from './comment.model';
import { Post } from './post.model';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json'
  })
};
const baseUrl = 'http://my_base_url';

@Injectable({
  providedIn: 'root'
})
export class PostService {

  constructor(private http: HttpClient) { }

  getPosts(userID: any): Observable<Post[]> {
    /*
     * This method takes in a userID as a parameter and 
     * makes a Http get request to our Random Network API
     * in order to retrieve all Posts for this user.
     * Our result will be an observable containing an array of Posts.
     */
    return this.http.get<Post[]>(`${baseUrl}/postsData/${userID}?apiKey=1234`);
  }
}

profile.component.html

<div id="posts-area">
    <ul id="list-of-posts" >
      <li
        
        *ngFor="let post of posts; let i = index">
        <p >{{ post.postText }}</p>

        <ul id="list-of-comments" >
          <li
            
            *ngFor="let comment of post.comments">
            <!--The following line is producing Error: Property 'commentText' does not exist on type 'Comment'.-->
            <p >{{ comment.commentText }}</p>

          </li>
        </ul>

      </li>
    </ul>
</div>

CodePudding user response:

I've been caught out by this exact issue.

There is a built-in type called Comment. If you forget to import your own model, TypeScript defaults to the built-in type. I believe that your post.model.ts doesn't import your custom type.

Add the import and it should all work fine :-)

  • Related