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?
A
return
is missing andsubscribe
needs to be changedmap
to allow the async pipe to do the subscriptionand for async values the async pipe needs to be used