Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular / Typescript Class Getter property not working

I've a class as shown below

export class Story {
    id: number;
    title: string;
    storyText: string;
    utcDate: string;
    get displayDate(): string {
       const today = new Date();
       const postDate = new Date(this.utcDate);
       const td = today.getTime();
       const pd = postDate.getTime();
       return ((td-pd)/1000)+'ms';
    }
}

HTML view is shown below

<span>
   <i class="fa fa-clock-o" aria-hidden="true"></i>
   {{story.displayDate}}
</span>

Here, the html code block is inside and ngFor loop as *ngFor="let story of stories" and stories is an array of type Story , stories: Story[]; But its not displaying anything . No error also. What am I doing wrong here? Will this work like this without an explicit setter property? Or should I create a setter property and set the value manually?

edit: below my script that populate the story array and the service function

loadData() {
this.storyService.stories()
.subscribe(
data => {
  const response = <Story[]>data.message;
  this.stories = response;
},
error => {
    alert('error');
});

}

    stories() {
          return this.http.get<Result>(this.baseUrl + '/story/list/', this.httpOptions);

 }
like image 645
Manu Mohan Thekkedath Avatar asked Sep 03 '25 06:09

Manu Mohan Thekkedath


1 Answers

Your getter wont work unless you create a new instance. Also when you are putting stories: Story[], you are only telling that it is safe to assume Stories will contain properties in Story class. Typescript wont that there is a getter.

Since you are inside ngFor, I suggest using a Pipe.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'displayDate'
})
export class DisplayDatePipe implements PipeTransform {

  transform(value: any): string {
    const today = new Date();
    const postDate = new Date(value);
    const td = today.getTime();
    const pd = postDate.getTime();
    return ((td-pd)/1000).toString();
  }

}

then in your template make slight modification like this.

<span>
   <i class="fa fa-clock-o" aria-hidden="true"></i>
   {{story.utcDate | displayDate }}
</span>
like image 51
Niragh Avatar answered Sep 04 '25 23:09

Niragh