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;
});
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With