Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aurelia - value converter using promise

I need to format Date using format returned by promise. I tried returning promise from toView(value). But that doesn't work.

@autoinject
export class DateTimeValueConverter {

    constructor(private formatService:FormatService) {
    }

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

}

Here's FormatService's code, which works properly

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;
            });
        }
}
like image 877
Juri Krainjukov Avatar asked Apr 19 '16 08:04

Juri Krainjukov


1 Answers

As far as I know, you cannot use async functionality within value converters. One solution I see, is to pass the format as a parameter from the viewmodel to the value converter (through the view). But this means you need to fetch the format within the viewmodel, which kind of destroys the whole point of value converters...

Another solution I see, is to adjust FormatService so that it caches the format (assuming that 'format' doesn't change often). This way, the getFormat function will be synchronous and you can use it within the value converter. Of course, you will need to find a way to initialize format within FormatService before any value converters are called.

like image 113
fikkatra Avatar answered Oct 27 '22 22:10

fikkatra