我有一個服務從服務器獲取時間的方法,我打算在自定義管道中使用它。管道的目的是將時間戳與當前時間進行比較,並以可讀的格式返回。Angular 4 Pipes中的異步調用
服務
export class TimeService{
currentServerTime;
fetchCurrentTimeStamp(){
//http request using Observable
return sendGETRequest(.....).map(data => {
this.currentServerTime = data;
return this.currentServerTime;
})
}
}
管
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>
我卡與異步調用。只有在我從服務器獲取數據後,如何從管道中返回值?