How can I display and link a base64 string to an Image as a source in Nativescript?

I'm having trouble displaying and binding a base64 image as an ImageSource in my View. The image doesn't show up at all, and I couldn't find any helpful information about it in the documentation. Am I missing something?

The imageSource property is supposed to contain the Image src data.

Below is the code for 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 the 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 №1

After a quick glance at the code, it seems like you may have overlooked setting the _imageSource to trigger an update. While you are calling the method on the ImageSource instance, there is nothing in place to update the UI binding. Consider either creating a setter for the _imageSource or assigning it using Observable:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I pass JSON data from a Java Swing application to a servlet? Should I use HTTP or sockets for this task?

Currently, I am using Eclipse Indigo and Tomcat 7.0 for my project. The project named "Controller" under the package "gui" is a Swing application aimed at creating a controller-tool for managing machine information settings. Within this application, there ...

`Typescript does not adhere to the specified type when used inside a for loop with a local

This code snippet declares a variable venuelist of type Venue array and initializes it as an empty array. The type Venue has a property named neighborhood. There is a for loop that iterates through the venuelist array and checks if the neighborhoods matc ...

The parameter of type "Construct" cannot be assigned the argument of type "undefined"

I attempted to use code example from the AWS CDK documentation, but it did not function as I had anticipated. Using CDK version 2.62.2 with Typescript. In various parts of the code, a declaration error occurs stating that The argument of type "undefi ...

The Route.ts file does not export any HTTP methods

Encountering an error while trying to migrate code from Next JS 12 with pages router in Javascript to Next JS 13 with TypeScript. ⨯ Detected default export in 'vibe\src\app\api\auth[...nextauth]\route.ts'. Export a name ...

What could be causing Android to not show up in the preferences of Eclipse?

Following the official instructions on installing the Android Developer tools, I have successfully completed the process. However, I am facing an issue as the tab is not appearing in Windows->Preferences as stated in the guidelines. Can anyone help me ...

Node.js performance hindered by slow execution of Array.find(), causing frustration for users due to bad experience

This query does not involve concurrency or the event loop in node I am seeking advice on managing a situation where thousands of users are connected to a Node.js server via sockets and authenticated using JWT tokens. Let's imagine there are between ...

The optimal location to declare a constructor in Typescript

When it comes to adding properties in an Angular component, the placement of these properties in relation to the constructor function can be a topic of discussion. Is it best to declare them before or after the constructor? Which method is better - Method ...

Upon deployment, Angular encounters issues with routing to lazy loaded modules

I recently completed development on a new Angular application that utilizes lazy loading for improved performance. During local testing using ng serve (or ng serve --prod to mimic production mode), the app compiled without errors and functioned properly. ...

Unable to add chosen elements to array - Angular material mat select allowing multiple selections

Can anyone assist me in figuring out what I am doing wrong when attempting to push data to an empty array? I am trying to only add selected values (i.e. those with checked as true), but I can't seem to get inside the loop This is the current conditi ...

The app you recently submitted has been declined due to a violation of the guidelines set forth by the Google Play

(1) My app offers a simple education-based content and allows users to attempt tests without any Google ads, only integrating with YouTube. Users can login to this straightforward app by using an activation key provided by their institute. I received an ...

Creating dynamic class fields when ngOnInit() is called in Angular

I am trying to dynamically create variables in a class to store values and use them in ngModel and other places. I understand that I can assign values to variables in the ngOnInit() function like this: export class Component implements OnInit{ name: st ...

What is the reason behind the lack of exported interfaces in the redux-form typings?

I've been exploring how to create custom input fields for redux-form. My journey began by examining the Material UI example found in the documentation here. const renderTextField = ({input, label, meta: { touched, error }, ...custom }) => < ...

Give the Row ID as a parameter to a personalized component within MUI Datagrid Pro

I am currently exploring the idea of incorporating an intermediate state to row checkboxes based on the selection status of other checkboxes within a detailed panel. My approach involves crafting a custom checkbox component and implementing some logical ...

Blend the power of Node's CommonJS with the versatility of Typescript's ES modules

I currently have a Node.js v10 legacy application that was built using CommonJS modules (require). The entire codebase is written in JavaScript. However, I am considering upgrading the app and refactoring a specific part of it to use TypeScript modules ( ...

Crafting redirect rules in React that avoid redirecting to the same route

In my project, there is a file named AuthenticatedRoute.tsx, which serves as a template for all the protected/authenticated routes in my Router.tsx file. export default ({ component: C, authUser: A, path: P, exact: E }: { component, authUser, path, ex ...

Proper method for typing the generics of DatePickerProps belonging to the DatePicker component in mui-x library

I have a component called CustomDatePicker which has been configured for localization as shown below: function CustomDatePicker(props: DatePickerProps<unknown> & React.RefAttributes<HTMLDivElement>) { return ( <StyledDatePicker ...

When using Vue with Vuetify, be aware that object literals can only specify known properties. In this case, the type 'vuetify' does not exist in the ComponentOptions of Vue with DefaultData

Started a fresh Vue project with TypeScript by following this guide: https://v2.vuejs.org/v2/guide/typescript.html If you don't have it installed yet, install Vue CLI using: npm install --global @vue/cli Create a new project and choose the "Manual ...

Heroku build is reporting that it cannot locate the `@types` in the package.json file

Encountered Heroku Build Error - TSError: ⨯ Struggling to compile TypeScript: - src/server.ts(1,38): error TS7016: File declaration for module 'express' not found. '/app/node_modules/express/index.js' is implicitly of type 'any&a ...

What are the steps for integrating Angularfire2 into an Angular application?

Trying to integrate Angularfire2 into a fresh Angular project, but encountered an issue while following the official documentation. This is the guide I followed Upon reaching step 7 - Inject AngularFirestore, console errors were displayed: If anyone has ...

Leveraging Array.map within Angular Interpolation

Is it possible to achieve the following in HTML using Angular 2+? {{ object.array.map((o) => o.property ) }} Whenever I try to execute this code, it crashes the Angular application. Do I need to utilize Pipes or any other technique? ...