I
I
Ivan-P2017-02-09 17:42:26
JavaScript
Ivan-P, 2017-02-09 17:42:26

How to start timer in Angular2 pipe?

There is a pipe that shows the time difference.

import {Pipe} from "@angular/core";

@Pipe({name: 'ago'})
export class AgoPipe {
  transform(date: Date): string {
    return timeDifference(date);
  }
}

function timeDifference() {...}

timeDifference is a transformation function that returns "20 seconds ago" for example. But the pipe runs only 1 time, how to make it recalculate, for example, once every 10 seconds?
I came up with a partial way out through the use of a component
import { Component, Input } from '@angular/core';
import { Subscription, Observable } from 'rxjs';
@Component({
  selector: 'ago-renderer',
  template: `<span>{{ago}}</span>`,
  styles: [`:host {display: inline}`]
})

export class AgoRendererComponent {

  @Input() time: any;
  timer: Subscription;
  ago: any;

  ngOnInit() {
    this.timer = Observable.interval(5000).subscribe(() => {
      this.ago = timeDifferenceHumanise(this.time);
    });
  }

  ngOnDestroy() {
    this.timer.unsubscribe();
  }
}

But still want Pipe

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Pavlov, 2017-02-09
@joseperez

Run it through the async pipe. In async pass Observable.timer

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question