Xoyce Xoyce - 1 month ago 9
TypeScript Question

How to show and bind base64 string to Image as a source in Nativescript?

I am trying to show and bind base64 image as ImageSource in my View, but it does not show up at all. I couldn't find any helpful information on this in documentation .. am I doing something wrong?

imageSource is property that should hold Image src data ..

Here is the View:

<Page loaded = "loaded" xmlns = "http://schemas.nativescript.org/tns.xsd" >
<StackLayout>
<TextField hint = "String for encoding!" text = "{{ message }}" />
<Button tap = "{{ onGenerateQrTap }}" text = "Generate QR" class = "button" />
<Image src = "{{ imageSource }} " />
</StackLayout>
</Page>


here is the code behind View:

import { Page } from 'ui/page';
import { EventData } from 'data/observable';
import { QrGeneratorViewModel } from '../../ViewModels/QrGeneratorViewModel';
import { Button } from 'ui/button';
import { Image } from 'ui/image';

let viewModel = new QrGeneratorViewModel();

export function loaded(args: EventData) {
let page = <Page>args.object;
page.bindingContext = viewModel;
}


and here is the ViewModel:

import { Observable } from 'data/observable';
import { QrGenerator } from '../Common/QrGenerator';
import { ImageSource } from "image-source";

export class QrGeneratorViewModel extends Observable {

private _message: string;
private _qrGenerator: QrGenerator.Generator;
private _imageBase64String: string;
private _imageSource: ImageSource;

constructor() {
super();
this._qrGenerator = new QrGenerator.Generator();
this._imageSource = new ImageSource();
}

get message() {
return this._message;
}

set message(newMessage: string) {
this._message = newMessage;
}

get imageSource(): ImageSource {
return this._imageSource;
}

public onGenerateQrTap(): void {
this._imageBase64String = this._qrGenerator.qr(this._message);
this._imageSource.loadFromBase64(this._imageBase64String);
}

}

Answer

Quickly skimming the code it doesn't look like you are setting the _imageSource for it to update. You call the method on the ImageSource instance but nothing to set the UI binding. I would try having a setter for the _imageSource or setting it with the Observable:

this.set('imageSource', this._imageSource.loadFromBase64(this._imageBase64String);

Comments