gpt4 book ai didi

angular - Angular 4 Pipes 中的异步调用

转载 作者:行者123 更新时间:2023-12-02 10:00:45 26 4
gpt4 key购买 nike

我有一个服务方法,可以从服务器获取时间,我计划在自定义管道中使用它。该管道的目的是将时间戳与当前时间进行比较,并以人类可读的格式返回。

服务

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>

我被异步调用困住了。如何仅在从服务器获取数据后才从管道返回值?

最佳答案

缺少return,并且subscribe需要更改map以允许异步管道进行订阅

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

对于异步值,需要使用异步管道

<span>{{model.created | getTimeFromNow | async }}</span>

关于angular - Angular 4 Pipes 中的异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45919133/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com