Ionic 2: Image source not being updated

When working with Ionic 2, I encountered an issue where the src attribute of an <img> element was not updating inside the callback function of a plugin.

Here is the template code:

<img [src]="avatar_path" id="myimg" />

After using the Camera plugin, the following code snippet was employed:

navigator.camera.getPicture( imageBase64 => {
    this.avatar_path = 'data:image/png;base64,' + imageBase64;
},
error => {
    console.log(error)
}, {
    sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
    destinationType: 0,
    allowEdit:true,
    sourceType: 2
})

Unfortunately, nothing happened. However, manually setting the src attribute using plain JavaScript worked:

document.getElementById("myimg").src = 'data:image/png;base64,' + imageBase64;

Addtionally, if I set the avatar_path value outside the callback function, it works as expected:

this.avatar_path = 'data:image/png;base64,someharcodedbase64data';

It appears that the view is not updating within the callback function. In Ionic 1, I would handle such situations by re-rendering the view using $scope or a similar method, but I am unsure about the best practices for addressing this issue in Ionic 2.

Answer №1

To ensure proper execution, it is recommended to run the code

this.avatar_path = 'data:image/png;base64,' + imageBase64;
within NgZone.

Consider using the following snippet of code:

import {NgZone} from 'angular2/core';
...
constructor(_zone: NgZone) {
   this._zone = _zone;
}
... 
navigator.camera.getPicture( imageBase64 => {
this._zone.run(() => {
    this.avatar_path = 'data:image/png;base64,' + imageBase64;      
});
}

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

Is there a way to mimic this type of scrolling effect?

Upon visiting this website, it is evident that the entire interface has been constructed with React. The scrolling experience on this site is exceptionally smooth, although it may feel slightly more substantial than a typical scroll. After researching onli ...

Styling with CSS: Using a Base64 Encoded Image in the Background URL

Can a Base64 encoded image be loaded as a background image URL without exposing the actual encoded string in the page source? For example, if a Node API is used to GET request at "/image", it returns the serialized Base64 data. res.json("da ...

The backend post request is returning only "undefined" in JavaScript

Hey there, I'm still learning JS so please bear with me. I've been working on incrementing a value in a JSON file within my JS backend app. However, whenever I try to increase the associated value by the key, it ends up creating a new section la ...

Puppeteer encountered an error when trying to evaluate the script: ReferenceError: TABLE_ROW_SELECTOR was not defined

https://i.stack.imgur.com/PJYUf.jpg Recently, I started exploring pupeteer and node while using vscode. My goal is to log into a website and scrape a table. So far, this is what I have: (async () => { const browser = await puppeteer.launch({ headle ...

The interface vanishes upon the integration of TinyMCE into the module

Currently, I am working on a project using Angular-fullstack and attempting to integrate ui-TinyMCE. However, I encountered an issue when I made the following changes: angular.module('academiaUnitateApp') .controller('NewEntryCtrl', ...

Personalized JavaScript Arrays

Seeking assistance to format data received from an API. Can anyone provide guidance? fields: [ { name: "A", values: { data: [1, 2, 3, 4, 5] } }, { name: "B", values: { data: [6 ...

Accessing a secured Azure AD CORS WebAPI with an AngularJS Single Page Application

After successfully implementing the SinglePageApp-DotNet example, I encountered a challenge when trying to make the single page application call a CORS enable web api. Both applications are secured by AAD and deployed to Azure websites, but I couldn't ...

Refreshing a component in React when a prop changes

My understanding is that React components update when their props or state change. For example, I declare a variable like this: let percentage = { width: '10%', }; Then, I have a function using setInterval to upd ...

Can you explain the functionality and process of scope.$new(true)?

I need assistance with testing a directive (more information available at: Unit testing angular directive - very stuck) I am particularly confused about the meaning of scope.$new(true). It seems like $new creates a new child scope, but I'm unsure abo ...

Continuously update scrolling functionality

Could you please provide more information about the solution mentioned in the following question? I am facing a similar issue. jQuery’s css() lags when applied on scroll event Regarding solution #3 ->> To ensure continuous updates, it is suggeste ...

Angular directive has issues with $compile functionality

This Angular directive automatically appends a new HTML item to the page every time my model changes: app.directive('helloWorld', function($compile) { return { restrict: 'AE', replace: true, scope:{ ...

The SmoothShading feature of THREE does not alter the geometry

I am having trouble with smooth shading on my model - the polygons are still clearly visible and switching between smooth and flat shading in the three.js inspector isn't making a difference. The OBJ file contains vertex normal data, so I don't t ...

Process JSON data from an input using Javascript

I am encountering an obstacle at the final step of my data flow process. Currently, I am in the midst of developing an application that retrieves input from an HTML form field and utilizes Ajax to fetch data relevant to the user's input. Allow me to e ...

The function $provide is not recognized while executing a Karma test

Experiencing an issue while testing an angular service with karma: Error: [$injector:modulerr] Failed to instantiate module function ($provide) due to: TypeError: $provide is not a function at K:/home/projects/tmp/mobile/test/myservice.Spec. ...

Using a loop to execute Javascript Promise.all()

I am currently facing an issue where I need to make a web API call twice inside a loop, and then wait for the results before pushing them into a larger array as subarrays. The code snippet below illustrates my approach: var latlngPairs = []; function extra ...

having trouble transferring data from one angular component to another

I've been attempting to send data from one component to another using the service file method. I've created two components - a login component and a home component. The goal is to pass data from the login component to the home component. In the l ...

The property of undefined map cannot be read

import React from 'react'; import { Card, Text } from "react-native-paper"; import { SafeAreaView, } from "react-native"; class HackerNewsClone extends React.Component { constructor(props) { super(props); this.sta ...

Using jQuery DataTable to fetch JSON data upon Document Loaded

I am struggling to implement a PHP script that returns JSON data to populate a DataTable. The PHP script 'api/exceptions_all.php' is as follows: <?php $select = "SELECT '', [FOR_PARTNER], [FOR_NAME] FROM [brokerage].[dbo].[for_ex ...

How can I target the first checkbox within a table row using jQuery?

I am seeking a way to determine if the first checkbox in a table row is selected, rather than checking all checkboxes within that particular row. Currently, I am using this code: var b = false; $j('#tb1 td input:checkbox').each(function(){ ...

Comparing the distinction between assigning values to res and res.locals in a Node.js application using Express

Greetings! I am inquiring about the utilization of res (Express response object) and res.locals in Express. During my exploration of nodejs, I came across a code snippet that consists of a middleware (messages.js), a server (app.js), and a template (messa ...