Assign the image source to the file path located in the data directory

Is there a way to dynamically set the src attribute of an <img> tag in an HTML file using a string path from a file?

The path is retrieved from the cordova.file.dataDirectory Cordova plugin within Ionic2 (TypeScript) and it typically looks like this:

UPDATED TO DISPLAY MY CODE:

This snippet shows the relevant section of the profile.ts code

...
import {Camera} from "ionic-native";
...
import {API} from "../../services/api";
import {ImageAdquistionService} from "../../services/imageAdquisition.service";
...
import {Network,File} from 'ionic-native';




declare let cordova: any;


@Component({
  selector:    'page-profile',
  templateUrl: 'profile.html'
})

export class ProfilePage implements OnInit{


  connected:boolean = false;

  imagePath: string = "./assets/img/pio.jpg";
  userInfo: User = new User();


  constructor(

              private api:API,
              private imageAdquistionService: ImageAdquistionService,
              ){

    //seleted tab by default
    this.tabs="info";

    this.connected = Network.type !== "none";

  }

  ngOnInit(): void {

    this.localStorageService.getUserInfo().then(user => {
      this.userInfo = user;
      if (this.userInfo.imagenPerfil !== "defAlert") {

        File.checkFile(cordova.file.dataDirectory,this.userInfo.profileImage).then(result => {
         console.log("exist")
          this.imagePath = cordova.file.dataDirectory + this.userInfo.profileImage;
         })
         .catch(error => {
         console.log("not exist " + JSON.stringify(error))
         })
      }
    });

  }

  /* The rest of the code remains the same */

}

This part showcases the key points of the imageAdquisitionService code

/* The imageAdquistionService code block */

This excerpt demonstrates the essential aspects of the API service code

/* The api service code block */

Lastly, here is the pertinent snippet of the HTML code

<ion-item no-lines class="item-bar-profile">
      <ion-avatar>
        <img class="centered" src="imagePath" (click)="presentOptions();">
      </ion-avatar>
</ion-item>

This example uses a hardcoded default image path:

this.imagepath = "./assets/img/pio.jpg"

https://i.sstatic.net/tLsV5.png

Here's what happens when programmatically changing the path:

this.imagepath = file:///data/user/0/com.ionicframework.myionicproject494629/files/58db7e92be26f32d4c8c01d2_1491989021049.jpg

https://i.sstatic.net/LS9sW.png

Thank you!

Answer №1

Encountered a similar issue myself. After some troubleshooting, I found out that running an android device live in Ionic was causing a conflict with cordova plugins. To fix this, instead of using ionic cordova run android -l -c, I had to opt for ionic cordova run android.

Answer №2

This is not the correct way to write the code [src]="this.imagepath". It is unnecessary to include this in this context.

A better approach would be:

file.html

[src]="imagepath"

Answer №3

Avoid using this with [src]="this.imagepath".

In my opinion,

[src]="imagepath"

or

src={{imagepath}}

should do the trick.

NOTE: The above solutions assume that

file:///usr...package....image.jpg
is a valid path.

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

In Angular 6, triggering a reset on a reactive form will activate all necessary validators

As a beginner in angular 6, I am currently facing an issue with resetting a form after submitting data. Although everything seems to be functioning properly, when I reset the form after successfully submitting data to the database, it triggers all the req ...

What is the best way to transform a string into emojis using TypeScript or JavaScript?

Looking to convert emoji from string in typescript to display emoji in html. Here is a snippet of the Typescript file: export class Example { emoji:any; function(){ this.emoji = ":joy:" } } In an HTML file, I would like it to dis ...

Tips on typing the onFocus function event parameter for a Material UI Input component

Currently, I am working on a custom dropdown using material ui components like Input and Popper. The goal is to have the popper open when the user focuses on the input field. Additionally, I am implementing this solution with TypeScript. import ClickAwayL ...

Set up variables during instantiation or within the class declaration

Is there a preferred way to initialize class variables in ReactJS with TypeScript - in the constructor or when declaring the variable? Both methods seem to work equally well and result in the same transpiled javascript. export class MyClass extends Reac ...

Streamline imports with Typescript

Is there a way to import modules with an alias? For example, I have an angular service in the folder common/services/logger/logger.ts. How can I make the import look like import {Logger} from "services" where "services" contains all my services? I've ...

Error: Failed to retrieve the name property of an undefined value within the Array.forEach method

Upon pressing the button to display the task pane, I encountered an error message in the console window that reads: "Uncaught (in promise) TypeError: Cannot read property 'name' of undefined". This error persists and I am unable to resolve or com ...

Locate and embed within a sophisticated JSON structure

I have an object structured as follows: interface Employee { id: number; name: string; parentid: number; level: string; children?: Employee[]; } const Data: Employee[] = [ { id:1, name: 'name1', parentid:0, level: 'L1', children: [ ...

Using the spread operator in the console.log function is successful, but encountering issues when attempting to assign or return it in a

Currently facing an issue with a spread operator that's really getting on my nerves. Despite searching extensively, I haven't found a solution yet. Whenever I utilize console.log(...val), it displays the data flawlessly without any errors. Howev ...

Angular integration problem with aws-amplify when signing up with Google account

I am attempting to integrate AWS-Amplify(^4.3.0) with angular-12 and typescript (4.3.5). I have followed the documentation to configure amplify properly, but when trying to start the app, I encountered some amplify errors as shown below. Warning: D:\G ...

Component in Angular with an empty variable in TypeScript

I'm encountering an issue on my web page where I have a loop calling a component multiple times. I successfully pass data to the component, but the problem arises when I try to display the value of an object in the component. In the component's H ...

The Relationship Between Typing Variables and Generic Types in Functions

I need help implementing a specific function type: type TestType<T extends HTMLElement> = (input: T) => React.Ref<T>; I have a variable that I want to be typed with the above type for strict type guarantees on the return type: const Test ...

Resolving Hot-Reload Problems in Angular Application Following Upgrade from Previous Version to 17

Since upgrading to Angular version 17, the hot-reload functionality has been causing some issues. Despite saving code changes, the updates are not being reflected in the application as expected, which is disrupting the development process. I am seeking ass ...

Can data from an Angular app be accessed by an external JavaScript code within the same project?

I've been thinking about a theoretical scenario that luckily I haven't encountered yet. Imagine I have an Angular Project compiled in My PROJECT FOLDER. <br/> Inside this PROJECT FOLDER, there's another JAVASCRIPT FILE external to ...

Not all generic types specified with an extends clause are appropriately narrowed down as expected

Consider the following scenario: type MyType = 'val1' | 'val2' | 'val3'; const variable = 'val1' as MyType; const val2 = 'val2'; const val3 = 'val3'; declare function test<U extends MyType&g ...

Understanding Angular's Scoping Challenges

I have a function that retrieves an array and assigns it to this.usStates. main(){ this.addressService.getState().subscribe( (data:any)=>{ this.usStates = data; if(this.usStates.length===0) { this.notificationServic ...

Angular Material - Adding tooltips to Mat-table rows

I am currently working with Angular Material Mat-Table and I have a requirement to show a tooltip when hovering over any row. Essentially, I need to filter data from mGridDataSource based on the row id. Since I am new to Angular, I would greatly appreciate ...

"Activate the mat-checkbox based on the outcome of a certain process

I'm working with a mat-checkbox that triggers a mat-dialog when clicked. If the user clicks "confirm" in the dialog, I want the checkbox to be checked. If they click "cancel", I want it to remain unchecked. How can I achieve this? Below is the method ...

Utilize API within an array to enable Ionic to display a PDF in a document viewer

Recently diving into the world of Angular and Ionic, I've come across some interesting API data: [{"ID":"1","Title":"Maritime Safety","File_Name":"9c714531945ee24345f60e2105776e23.pdf","Created":"2018-11-07 17:36:55","Modified":"2018-11-07 17:36:55"} ...

Is it possible to extend the Object class in order to automatically initialize a property when it is being modified?

My experience with various programming languages leads me to believe that the answer is likely a resounding no, except for PHP which had some peculiar cases like $someArray['nonexistentKey']++. I'm interested in creating a sparse object whe ...

Displaying TypeScript issues across the entire project in WebStorm allows for a comprehensive overview

Is it possible to have Webstorm consistently report all TypeScript errors across an entire project without having to open each individual file? I prefer using the language service for performance reasons rather than running tsc as a task. I've notice ...