Saving an image from a URL directly to the assets folder: A step-by-step

I'm currently working on my first Android app using Ionic and Cordova. I need to fetch an image from a REST API and save it on the device so that it can be accessed offline.

Here are the versions I am using:

Ionic:

Ionic CLI : 6.10.1 (C:\Users\agusd\AppData\Roaming\npm\node_modules@ionic\cli) Ionic Framework : @ionic/angular 5.3.1 @angular-devkit/build-angular : 0.901.12 @angular-devkit/schematics : 9.1.12 @angular/cli : 9.1.12 @ionic/angular-toolkit : 2.3.0

Capacitor:

Capacitor CLI : 2.4.0 @capacitor/core : 2.4.0

Cordova:

Cordova CLI : 9.0.0 ([email protected]) Cordova Platforms : android 8.1.0 Cordova Plugins : cordova-plugin-ionic-keyboard 2.2.0, cordova-plugin-ionic-webview 4.2.1, (and 4 other plugins)

I followed a guide for Ionic 3 but couldn't make it work with my current version of Ionic.

So far, I have been able to retrieve the JSON object containing the image URL, but I'm unsure how to download and store the image in my assets folder.

My code looks like this:

api.service.ts:

apiURL = 'my api url...';
 getDiarios() {
    const diarioArgs = {
      method: 'GET',
      mode: 'cors',
      headers: {
        'Content-Type': 'application/json' }
    };
    return this.http.get(this.apiURL, diarioArgs);
  }

Then, I have this function that calls the service and retrieves the response:

data: any;
lastDiario: any;
lastID = 0;

loadLastDiario() {
    try {
      this.apiService.getDiarios().subscribe(
        (data) => {
          this.data = data;
          for (const item of this.data.content) {
            if (item.id > this.lastID) {
              // Get the object with the largest id, which is the latest uploaded
              this.lastID = item.id;
              this.lastDiario = item;
            }
          }
          console.log(this.lastDiario);
          for (const item of this.lastDiario.archivos) {
            // Need to save each item in "archivos" to my assets folder or elsewhere
            // Each item has a URL property accessible through **this.lastDiario.archivos.url**
          }
        }
      );
    } catch (error) {
      console.log("Couldn't connect to the service")
    }
  }

If anyone could offer assistance, as I'm new to Ionic and Angular, I would appreciate any advice!

Answer №1

During runtime, the assets folder is view-only.

It's only possible to save files in it while in the design phase.

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

Initially, when an iframe is loaded in Angular 10, it may display a 404 error page

Hey there! I'm currently using the HTML code below to incorporate an iframe and display an external page hosted on the same domain so no need to worry about cross domain issues: <iframe frameborder="0" [src]="url"></iframe ...

Utilize nodemailer in Angular 6 to effortlessly send emails

I am currently experiencing an issue with my email service form in my Angular 6 application integrated with Node.js. I have set up the form using Bootstrap and Nodemailer for sending emails, but it seems to not be working as expected. Whenever I attempt to ...

Navigating through JSON object array using *ngFor directive in Angular 4

I am trying to iterate through an array of objects stored in my JSON file. JSON [ { "name": "Mike", "colors": [ {"name": "blue"}, {"name": "white"} ] }, { "name": "Phoebe", "colors": [ {"name": "red"}, { ...

Effortlessly collapsing cards using Angular 2 and Bootstrap

Recently delving into Angular 2 and Bootstrap 4, I set up an about page using the card class from Bootstrap. Clicking on a card causes it to expand, and clicking again collapses it. Now, I want to enhance this by ensuring that only one card is open at a ti ...

GraphQL Error: Invalid syntax - expecting a Name but found $

Facing an issue with updating data in GraphQL (Angular Apollo) as I receive the error message GraphQLError: Syntax Error: Expected Name, found "$" This is what I am doing: const CONFIRM_CITA = gql` { mutation changeConfirmationStatus ($cen ...

Eliminate duplicate dropdown options in Angular 2 using a filter function

Is there a way to filter reporting results in an Angular 2 dropdown list? I am currently attempting to do so within the *ngFor template but haven't had any success. I will also try using a custom pipe. The data is coming from a JSON array. Specificall ...

Dynamically add a new column to a material table and modify the column title in-line when clicked

I am attempting to create a material table where I can dynamically add or remove columns and rows upon button click. I have tried to implement the following code: displayedColumns: string[] = ['name', 'weight', 'symbol', &apo ...

What could be causing issues with my Angular and Express.js Server-Sent Events implementation?

Objective: Implement Server-Sent Events in Angular App with Express Backend Issue: Client does not receive Server-Sent Events Backend Implementation router.get('/options/:a/:b/:c', async (req, res) => { console.log('options endpoint c ...

Updating a component's value in Angular 6 when there is a change in the corresponding service

My objective sounds straightforward, but I am struggling to implement it: I want one of my components to automatically update when a variable in a service changes. To illustrate my issue, consider the following example: Imagine having a service that incr ...

How can I extract only the pure HTML elements, not custom elements, from a div in Angular?

How can I extract pure HTML code from a specific div in Angular? I have tried using document.getElementById but it retrieves Angular type HTML with custom tags. I require plain HTML tags in order to create a PDF, as the browser needs to understand the HT ...

What is the best way to set the typing of a parent class to the child constructor?

I am seeking a method to inherit the parameter types of a parent's constructor into the child's constructor. For example: class B extends A { constructor (input) { super(input); } } I attempted the following: class B extends ...

Invoking functions from an array of TypeScript union types

Within my Typescript array, I have two classes: StripeCardModel | StripeBankModel Both of these classes extend StripePaymentModel My goal is to locate a specific class within the array that can potentially contain instances of both classes. Once found ...

An effective way to extract targeted information from an array of objects using Typescript

I'm having trouble extracting the IDs from the selected items in my PrimeNG DataTable. Despite searching on Google, I couldn't find much information about the error I'm encountering... ERROR in C:/Users/*****/Documents/Octopus/Octopus 2.0/s ...

Angular allows for dynamic sourcing of iframes

I have encountered an issue while trying to integrate a payment system with Angular. The payment gateway API I am using provides the 3D Secure Page as html within a JSON response. My approach is to display this html content within an iframe, however, the h ...

Issue: The system was unable to locate com.android.tools.build:gradle:2.2.3

Issue: Unable to locate com.android.tools.build:gradle:2.2.3. Search performed in the following directories: https://repo1.maven.org/maven2/com/android/tools/build/gradle/2.2.3/gradle-2.2.3.pom https://repo1.maven.org/maven2/com/a ...

What is the process for importing a .webp file into a TypeScript file to be utilized in an Angular project down the line?

I created a Weapon class with at least one icon. export default abstract class Weapon { icons: string[]; // Possibly incorrect type constructor(iconOrIcons: string | string[]) { this.icons = typeof iconOrIcons === 'string' ? [iconOrIcons ...

Using Typescript for testing React components: successfully passing an array of objects as props

My current approach involves passing an array of objects to mock component data for testing: const mockPackage = { id: '1232-1234-12321-12321', name: 'Mock Package', price: 8.32, description: 'Mock description', glo ...

Is ngModel the appropriate method for connecting a form to server-side scripts?

Just diving into the world of Angular, I'm embarking on my very first project - a hybrid mobile app using Ionic/Angular. Within my app, each user has their unique notification settings. There are ten different types of notifications that users can to ...

Retrieve the parent document for every item within a Firebase collection group

Transitioning from an SQL background to document storage, I am currently navigating through a Firebase database structure that looks like this: John (doc) Restaurant Reviews (collection) Review 1 (doc) Review 2 (doc) Paul (doc) Restaurant Reviews ...

Utilize Jquery to interact with Android's date picker interface

Currently, I am developing an application for IOS and Android using Phonegap with Cordova 2.2.0. In my development process, I am utilizing jQuery and HTML5 technologies. While working on the IOS version, I found that simply setting the input type to "dat ...