我有一个棱角分明的应用程序,我想实现“ Time Ago”功能。如果我提出一些疯狂的“问题”,这是一个坏主意吗?

如果您能想象有一条Facebook帖子,上面写着“大约在一分钟前发布...”,那就是我的目标。

假设用户从未刷新过页面,而是将问题从信号中心接收到有角度的mdoel。

export interface IQuestion {
  timeAgo: string;
}

export class Question implements IQuestion {
  public timeAgo: string;
  constructor(question: IQuestion) {
    this.timeAgoTicker();
  }
  timeAgoTicker(): void {
    this.timeAgo = 'just now';
    setTimeout( () => this.timeAgo = 'about a minute ago', 10000);
    setTimeout( () => this.timeAgo = 'a couple of minutes ago', 20000);
    setTimeout( () => this.timeAgo = '5 minutes ago', 50000);
    // etc...
  }
}

最佳答案

我不知道有很多setTimeout调用会对性能产生什么影响,但是我宁愿将timeAgo设置为日期对象,然后在每次更新UI时检查now和该日期对象之间的区别:

export interface IQuestion {
  createdAt: Date;
}

export class Question implements IQuestion {
  public createdAt: Date;
  constructor(question: IQuestion) {
    this.createdAt = new Date();
  }

  getAge(): String {
    return (new Date() - this.createdAt).toSomeStringAccordingToAge()
  }
}


我不知道语法是否正确,因为我不使用Typescript。例如,如以下提到的评论之一所述,最好使用访问器(getter)。

10-05 20:51
查看更多