Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous calls in Angular 4 Pipes

I have a method on a service which fetches time from the server and I plan to use it in a custom pipe. The purpose of the pipe is to compare the the a timestamp to the current time and return it in human readable format.

Service

export class TimeService{
  currentServerTime;

  fetchCurrentTimeStamp(){
     //http request using Observable
     return sendGETRequest(.....).map(data => {
        this.currentServerTime = data;

        return this.currentServerTime;
     })
  }
}

Pipe

export class GetTimeFromNowPipe implements PipeTransform{

   fromNow;
   currentServerTime: number;
   constructor(private timeService: TimeService, private appSettings: AppSettings){}

   transform(value: number){
        var currentTime;
        this.timeService.fetchCurrentTimestamp().subscribe(data => {
            currentTime = data
            if(!value) return "";

            if(value){
               let newDate = moment.unix(value);
               this.fromNow = newDate.from(moment.unix(currentTime), true);
            }
          return this.fromNow;
        });

   }
}

HTML

<ul>
    <li *ngFor = "let model of models">
        <span>{{model.created | getTimeFromNow}}</span>
    </li>
</ul>

I'm stuck with the Async calls. How do I return the value from the pipe only after I fetch the data from the server?

like image 895
adityav Avatar asked Feb 25 '26 23:02

adityav


1 Answers

A return is missing and subscribe needs to be changed map to allow the async pipe to do the subscription

return this.timeService.fetchCurrentTimestamp().map(data => {

and for async values the async pipe needs to be used

<span>{{model.created | getTimeFromNow | async }}</span>
like image 96
Günter Zöchbauer Avatar answered Feb 28 '26 14:02

Günter Zöchbauer