Unable to generate or compose a text document within my Ionic application

After attempting to create a file and write in it, I'm encountering an issue where the file appears to be created but is not visible when navigating to the folder. Can someone please point out what might be going wrong?

Below is my code snippet:

this.file.createFile(this.file.dataDirectory, array.ERROR + '_error', true).then(() => {
                    console.log("Created the file!" + this.file.dataDirectory.toString());
                  }).catch(err => console.log(err));


                  let blob_toSend = new Blob([this.inputxml], { type: 'text/plain' });
                  this.file.writeFile(this.file.dataDirectory, array.ERROR + '_error', blob_toSend, {replace: true, append: false}).then(() => {
                    console.log("Wrote the file!");
                  }).catch(err => console.log(err));

I also attempted to name the file as "_error.txt" but encountered the same issue where it doesn't show up. Any guidance on resolving this problem would be greatly appreciated.

Answer №1

Within your typescript file:

export class HomePage {
  fileValue:string;
  constructor(private plt:Platform,private file: File) {}

  checkValueExist(){
    return (this.fileValue);
  }

  createFile(){
    if(this.checkValueExist()){
      this.file.createFile(this.file.dataDirectory,this.fileValue,true).then(xfile=>{
        let filePath = xfile.nativeURL.substr(0, xfile.nativeURL.lastIndexOf('/') + 1);
        if (this.plt.is('android')) {
          this.copyToAppAndroidDir(filePath, xfile.name, this.createFileName(xfile.name));
        }else{
          this.copyToAppIosDir(filePath, xfile.name, this.createFileName(xfile.name));
        }
      }).catch(err=>{
        alert('File Not Created cause of : '+ JSON.stringify(err));
      })
    }else{
      alert('empty text');
    }
  }

  createFileName(name) {
    var newFileName = name + ".txt";
    return newFileName;
  }

  copyToAppAndroidDir(namePath, currentName, newFileName) {
    this.file.copyFile(namePath, currentName, this.file.externalDataDirectory, newFileName).then(success => {
      alert('done');
    }, error => {
      console.log('err :', error);
    });
  }
  copyToAppIosDir(namePath, currentName, newFileName) {
    this.file.copyFile(namePath, currentName, this.file.dataDirectory, newFileName).then(success => {
      alert('done');
    }, error => {
      console.log('err :', error);
    });
//here in the this.file.dataDirectory for ios it may work or could be tempDirectory since in reality i have android device and don't know where ios store its files so you can change when testing on ios and know the directory.
  }
}

And within the html:

<ion-input type="text" [(ngModel)]="fileValue"></ion-input>

  <ion-button color="primary" shape="round" expand="block" (click)="createFile()">Create File</ion-button>

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

Tips for executing forEach on a promise?

I am currently working with a function that returns a promise of an array: async function functionReturningPromiseOfUserIDs(): Promise<string[]> My question is, can I use the forEach method on the array returned by this function? async function runF ...

How can I retrieve properties from a superclass in Typescript/Phaser?

Within my parent class, I have inherited from Phaser.GameObjects.Container. This parent class contains a property called InformationPanel which is of a custom class. The container also has multiple children of type Container. I am attempting to access the ...

Using TypeScript to Implement Content Security Policy Nonce

I encountered an issue with my TypeScript Express project while attempting to implement a CSP Nonce using Helmet. app.use(helmet.contentSecurityPolicy({ useDefaults: true, directives: { scriptSrc: ["'self'", (req, res) = ...

Guide on creating path aliases for Storybook webpack configuration

Currently, I am integrating Storybook with nextjs and webpack. Below is my configuration in .storybook/main.ts: import type { StorybookConfig } from '@storybook/nextjs'; const config: StorybookConfig = { ... framework: { name: '@sto ...

Unlocking Column Data Tooltips in Angular Datatables: A Step-by-Step Guide

I have a single datatable and was wondering how to implement tooltips for when hovering over table cells. I tried the following code snippet, which successfully populated the tooltips. However, I am interested in achieving the same functionality using Angu ...

Find all objects in an array that have a date property greater than today's date and return them

I have an array of objects with a property called createdDate stored as a string. I need to filter out all objects where the createdDate is greater than or equal to today's date. How can this be achieved in typescript/javascript? notMyScrims: Sc ...

Setting a callback function as a prop for react-paginate in TypeScript: A step-by-step guide

When using react-paginate, there is a prop called onPageChange with the following type: onPageChange?(selectedItem: { selected: number }): void; After implementing it like this: const onPageChange = (selected): void => { console.log(selected); } ...

Angular - developing a custom web element to enhance the project

Is there a way to convert a single module into a web component and integrate it within the same project? Specifically, I have 3 modules in my project and I am looking to transform only module1 into a web component and incorporate it seamlessly. Thank you! ...

Utilizing Express JS to make 2 separate GET requests

I am facing a strange issue with my Express API created using Typescript. The problem revolves around one specific endpoint called Offers. While performing operations like findByStatus and CRUD operations on this endpoint, I encountered unexpected behavior ...

What is the best way to define a precise return type for a JSX Element?

Is it possible to define a function that returns a Button element and what would the correct return type of the function be? For example: Ex: const clickMeButton = (): Button => { return ( <Button> Click Me </Button& ...

What strategies can I implement to streamline the use of these functions instead of creating a separate one for each textfield

Currently, I am learning how to use spfx with SPO (SharePoint Online). In my form, there are multiple text fields that need to be handled. I have two class components named A and B. Whenever a textfield in component B is typed into, a function sends the in ...

Is there a way to load an image onto the ngx-image-cropper without triggering the imageChangedEvent event?

My latest project involved creating a custom cropper using ngx-image-cropper, which allows for cropping and rotating images. For the sprint demo, I needed the images to be displayed as soon as the application loads without having to trigger the fileChangeE ...

Navigating with Angular 6 using routerlink in a child module with router-outlet specified in the parent component (app.component

I'm currently working with the RouterModule and encountering an issue with the routerLinks. The problem I am facing is that the routerLinks are not functioning properly (the anchor tags are not clickable). This issue arises because they are located w ...

What is the best way to transfer a variable between components in Angular without using the HTML page, directly within the components themselves?

Within the child component, I am working with a string: @Input() helloMessage:string; I am looking to assign a value to this string from another string in the parent component and utilize it within the child component without displaying the value in the h ...

Executing a Playwright test against various projects or URLs within a single test run

I've been grappling with this problem for the past few days. I've tried a few workarounds, but none of them have worked as expected. What I need is to run Playwright tests against multiple URLs. Currently, running tests in a single project works ...

Error message: The attempted import failed because ' is not exported from the module

I am facing an issue with resolving my problem. In a file named lama.d.ts, I have declared a class using the following code: export declare class lama { // code here } After that, I tried to import this class in another file within the same folder ...

Using the watch flag in TypeScript across multiple projects - A comprehensive guide

In my project, I have the following scripts section in the package.json: "watch": "?", "build": "npm run build:compactor && npm run build:generator && npm run build:cleaner", "build:lambda": ...

Instead of leaving an Enum value as undefined, using a NONE value provides a more explicit

I've noticed this pattern in code a few times and it's got me thinking. When you check for undefined in a typescript enum, it can lead to unexpected behavior like the example below. enum DoSomething { VALUE1, VALUE2, VALUE3, } f ...

Dynamic TypeScript property that can only be assigned values from an array during runtime

I'm currently struggling with specifying allowed values for a property in TypeScript. Within my interface, I have statically typed the property like this: interface SomeInterface{ prop: "bell" | "edit" | "log-out" } However, I am looking for a w ...

Material UI autocomplete is not detecting the options parameter as an array

I am currently working on implementing an autocomplete field that retrieves options from my component's state, which in turn fetches data from the backend. Here is a snippet of my component: export const Person: React.FC<PersonProps> = ({name, a ...