Warm tip: This article is reproduced from serverfault.com, please click

typescript-奥雷利亚

(typescript - Aurelia)

发布于 2016-04-19 08:30:38

我需要使用 promise 返回的格式来格式化日期。我尝试从 toView(value) 返回承诺。但这不起作用。

@autoinject
export class DateTimeValueConverter {

    constructor(private formatService:FormatService) {
    }

    toView(value) {
        return this.formatService.getFormat().then(format=>
            moment(value).format(format)
        );
    }

}

这是 FormatService 的代码,它可以正常工作

export class FormatService {

    private format;

    constructor(private http:AppHttp) {
        this.format= null;
    }

    public getFormat() : Promise<string>{

        if (this.format){
            var promise = new Promise<string>((resolve, reject)=>{
                resolve(this.format);
            });
            return promise;
        }

        return this.http.get('format')
            .then((format) => {
                if (format){
                    this.format= format;
                }
                return format;
            });
        }
}
Questioner
Juri Krainjukov
Viewed
0
fikkatra 2016-04-19 18:07:13

据我所知,你不能在值转换器中使用异步功能。我看到的一种解决方案是format作为参数从视图模型传递到值转换器(通过视图)。但这意味着你需要在视图模型中获取格式,这会破坏整个值转换器点......

我看到的另一个解决方案是调整FormatService以缓存格式(假设“格式”不经常更改)。这样,该getFormat函数将是同步的,你可以在值转换器中使用它。当然,formatFormatService调用任何值转换器之前,你需要找到一种在其中进行初始化的方法