Transmitting information from a modal component to its parent component in Angular using MDB

I encountered an issue with my CRUD application where uploaded files do not immediately appear on the page until I refresh it. The same problem occurs when trying to delete a file.

For deleting, I was able to fix it by subscribing to the onClose event on modal/popconfirm. However, I am facing difficulties in applying the same logic for other operations, such as converting the file to base64 format. Let me guide you through an example that works (onDelete) and then explain the code that is causing problems when adding a new file.

Working example: In this scenario, I subscribe to onClose and use removeFile to delete the file with the correct ID. This action takes place in the PARENT component, where I display the data. After the file deletion, I call getData() function to retrieve updated data without having to refresh the page.

openPopconfirm(event: Event, data: any) {
const target = event.target as HTMLElement;
this.popconfirmRef = this.popconfirmService.open(
  PopconfirmDeleteComponent,
  target,
  { position: 'bottom-left', data: { injectedData: data } }
);

this.popconfirmRef.onClose.subscribe(() => {
    this.apiService.removeFile(data.IdMultimedia).subscribe(() => {
      this.getData();
    });
});

}

In the popconfirm (modal) component, I simply call this.popconfirmRef.close() to dismiss the popup.

Example, which I can't get working: The commented part in the code seems structured correctly, but I'm struggling to implement the right logic within this.modalRef.onClose.subscribe()

  openModalImage() {
this.modalRef = this.modalService.open(UploadImageComponent);
/*   this.modalRef.onClose.subscribe(() => {
    this.apiService.uploadFiles(formData).subscribe(() => {
      this.getData();
    });
});  */
}

(The code functions properly, but requires a page refresh after uploading a file to see the changes) At present, in the child component, I perform the following actions:

 // Transform file to base64
 convertFile(file: File): Observable<string> {
const result = new ReplaySubject<string>(1);
const reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = (event: any) =>
  result.next(btoa(event.target.result.toString()));
return result;
}

// Transform file when selected via input field
   onFileSelected(event: any) {
     this.selectedFile = <File>event.target.files[0];
    this.convertFile(this.selectedFile).subscribe((base64) => {
      this.base64Output = base64;
    });
    this.fileOnHold = true;
  }

// On click upload function
onUpload() {
this.data = {
  fileName: this.selectedFile.name,
  nadomestnoBesedilo: this.nadomestnoBesedilo,
};

const formData: any = {
  IdProfilDelodajalca: this.IdProfilDelodajalca,
  Tip: 2,
  VsebinaBin: this.base64Output,
  VsebinaTekst: this.nadomestnoBesedilo,
};

this.apiService.uploadFiles(formData).subscribe(() => {});   

this.modalRef.close(true);
}

If additional HTML code is required, please let me know. Thank you for your assistance!

Answer №1

It seems like there is a need to make some adjustments in this particular section of code:

Before:

this.apiService.uploadFiles(formData).subscribe(() => {});               
this.modalRef.close(true);

After:

this.apiService.uploadFiles(formData).subscribe(() => {
    /* Add your custom logic here */        
    this.modalRef.close(true);
}); 

Based on the current implementation, the modal is being closed prematurely without waiting for the upload process to complete.

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

I encountered an issue stating "The state contains a value that is not serializable," specifically related to data retrieved from a Calendar component

Encountering an error in the app stating that a non-serializable value has been detected in the state, particularly related to the date format from the Calendar component in PrimeReact. Researching the issue suggests that the problem lies in the property h ...

Angular web application can retrieve JSON data from a web API controller, allowing for

I'm currently utilizing ASP.NET Core on the backend and Angular on the frontend. My API delivers data in JSON format from the backend. I've set up a service to fetch the API data, but it's returning 'undefined' at the moment. emp ...

Angular 8: Bridging the gap between two players with a shared singleton service

I've been working on creating a multiplayer Battleships game, and although the basic functionality is there, I'm struggling to connect two players to the same game. Any assistance would be greatly appreciated! My goal is to create a service that ...

What is the best way to fetch a list of users from a Firebase database using angularFire without using a "key"?

I'm currently utilizing angularFire to establish a connection between my web page and my database. My objective is to showcase all the users saved in my firebase database in a list format on a specific page. The users are stored in the following manne ...

Running a Typescript ES6+ server-side with .NET Core and Node.js is made easy with Jering.Javascript.NodeJS. Learn how to set

I am trying to run some TypeScript code written in ES2020 on the server side. Currently, I have an ASP.NET Core application running, so my idea was to execute JavaScript via Jering.Javascript.NodeJS and Node.js. I started with a simple example. var test = ...

Error in Angular2: Attempting to access property 'af' of an undefined value leads to an exception

I'm currently working on an Angular2 application that utilizes Auth0 for authentication and AngularFire for database operations. I am facing an issue where I cannot access my AngularFire instance inside a callback event. Is there any alternative appro ...

What is the process of displaying events from components within ng2 submodules?

My dilemma involves two components with straightforward output events and handlers. I am attempting to pass a value from a child submodule to a component within my app.module. Here is the snippet of code from my app.component.ts: @Component({ selector: ...

Ensure that an input field is mandatory only when another field contains a value in Angular 6

I am working with two input controls in my Angular 6 project. The first control looks like this: <input type="text" [(ngModel)]="UserData.FirstControl" formControlName="FirstControl" class="form-control" maxlength="8" > T ...

What is causing the router.events to not fire for FooComponent in my Angular project?

Upon opening the following link , the eventsFromFoo entries in the console are nowhere to be found. It appears that this.router.events is failing to trigger for FooComponent. Any insights on why this might be happening? I am in urgent need of capturing t ...

There are missing dependencies for the designated entry point, "@vcd/ui-components."

Upon running the application with npm start from the branch named ryan-a11y-merge-to-master at https://github.com/juanmendes/vmware-cloud-director-ui-components, I encountered the following error. However, when I switch to the master branch, no errors are ...

Problem with Extending Jest Matchers in VS Code TypeScript

I've developed unique Jest matchers to enhance expect for handling AxiosResponse objects. Although I've followed the standard method for expanding Jest's matcher types, my custom matchers are not being recognized by TypeScript. The error di ...

TypeScript failing to recognize dependency for LitElement

Currently, I am encountering an issue with importing two lit elements in my project, namely RootElement and CustomElement. The problem arises when trying to import CustomElement, which unlike RootElement does not show up properly on the UI. My attempt to i ...

Add a new value to the translation token using ng-bind

I'm attempting to loop through an element 5 times using ng-repeat and track by $index. Following that, I aim to utilize the value from $index to supplement a translation token. This appended index value corresponds with the token which retrieves the a ...

Guide to accessing a nested and potentially optional object property with a default value and specifying its data type

Just a simple query here... my goal is to extract data.user.roles, but there's a possibility that data may be empty. In such cases, I want an empty array as the output. Additionally, I need to specify the type of user - which in this instance is any. ...

Guide on navigating to a specific step within a wizard using Vue and TypeScript

In this wizard, there are 6 steps. The last step includes a button that redirects the user back to step 4 when clicked. The user must then complete steps 5 and 6 in order to finish the wizard. step6.ts <router-link to="/stepFour" ...

Summing values in es6 (TypeScript) without explicitly knowing their corresponding keys

I am facing a challenge with an object that has changeable keys, which I do not want to rely on. The keys in this object are not fixed. Here is an example: interface Inf { [key: string]: number } const obj: Inf = { '2020-01-01': 4, '2 ...

After upgrading from angular-cli version 4 to version 7, the npm installation process stops working

I have been working on transitioning my Angular4 project to Angular7. Here are the steps I took in order to make this conversion: I first uninstalled the older version of angular-cli Next, I installed the latest updated version of angular-cli However, up ...

Unable to bring in Angular2 bootstrap function

I am currently setting up a basic Angular 2 (beta 2) app using TypeScript. I have the code for app.ts file taken from Angular's most recent setup guide import {Component, View, bootstrap} from 'angular2/angular2'; @Component({ selector: ...

Issues with tsconfig Path Aliases in Angular 8+ when used in .spec files

While working on Angular testing, I encountered an issue where my spec files were not recognizing paths and displaying a red squiggle import warning in VS Code (and appearing under Problems), even though they functioned properly otherwise (testing worked, ...

What is the correct way to close an ngx-contextmenu in an Angular application?

In my angular project, I implemented an ngx-contextmenu. Within one of my components, the template includes the following code: <div... [contextMenu]="basicMenu"> <context-menu>..... </div> After some time, the component with the conte ...