繁体   English   中英

使用setInterval的Angular 2 Observable无法在模板中使用异步管道进行更新

[英]Angular 2 Observable with setInterval not updating in template using async pipe

我有一个名为Task的模型类。 在其中,我通过创建一个返回可观察到的函数来获得运行时间。

public getRunningTime(): Observable<number> {
    const runningTimeObservable = new Observable<number>(observer => {
        setInterval(() => {
            if (this.isActive) {
                const currentTime = new Date().getTime();
                observer.next(currentTime - this.startTime);
            }
            observer.next(this.endTime - this.startTime);
        }, 5000);
    });
    return runningTimeObservable;
}

我将此任务模型绑定到一个名为TaskListComponent的组件。 该组件保留一个包含每个任务的对象。

export class TaskListComponent {

  tasks: object;

  constructor(
    private taskRepositoryService: TaskRepositoryServiceService,
    private taskFactoryService: TaskFactoryService,
    private taskInputDialog: MatDialog) {
    this.tasks = taskRepositoryService.getAllTasks();
  }

我使用ngFor在模板中进行迭代。

<ul>
    <li *ngFor="let task of tasks | keyvalue">
        {{task.value._name}} - {{task.value._color}} <span *ngIf="task.value.startTime">- {{task.value.getRunningTime() | async}}</span>
        <button mat-button color="warn" (click)="removeTask(task.value)">Remove</button>
        <button mat-button (click)="updateTask(task.value)">Update</button>
        <button mat-button (click)="startTask(task)">Start</button>
    </li>
</ul>

我正在尝试使用{{task.value.getRunningTime() | async}}每5秒显示和更新一次运行时间{{task.value.getRunningTime() | async}} {{task.value.getRunningTime() | async}}但似乎无法在视图上呈现任何内容。

有什么帮助吗? 我不认为我在做这种可观察的权利...但是我不确定如何在我的Task模型上创建动态值...该值会在视图中不断更新。

看来您做对了。

虽然您可能在这里遇到了一个new Date().getTime()的异常new Date().getTime() ,但该角度异步管道会吞下。 尝试使用(new Date()).getTime()测试此假设。

如果我可以的话,请提供一些建议:

  • 使用Date.now()代替(new Date()).getTime()
  • map使用timer而不是Observable构造函数-会更容易。
  • 在模型中保持createdAt并将Observable移至控制器,在该控制器中您将重新计算值(如果您只想显示经过的时间,那么控制器是一个更好的选择)

希望这可以帮助。

如果我理解正确,是否要根据计时器执行异步操作? 使用RXJS Timer创建一个间隔触发的可观察对象,然后使用flatMap将该事件映射到更新视图模型的异步调用。 可能看起来像这样:

timer(0, 5000).pipe( flatMap(() => taskRepositoryService.getAllTasks()))
 .subscribe(tasks => this.tasks = tasks);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM