"ng2-file-uploader necessitates a browser refresh in order to function

I am currently utilizing ng2-file-upload within my Angular 10 project to allow users to upload their photos. The upload process is functioning correctly, but the issue arises when the newly uploaded photo does not automatically appear in the photo list without refreshing the browser. Ideally, I would like any new photo that is uploaded to be instantly displayed in the photo list without requiring the user to manually refresh the browser.

Below is a snippet from my component.ts file:

ngOnInit(): void {
    this.initializeUploader();
    this.loadStoreUserPhotos();
  }

  fileOverBase(e: any) {
    this.hasBaseDropzoneOver = e;  
  }      

  uploadFile(file: File) {
    this.memberService.uploadImage(file).subscribe((event: HttpEvent<any>) => {
      switch (event.type) {
        case HttpEventType.UploadProgress:
          this.progress = Math.round(event.loaded / event.total * 100);
          break;
        case HttpEventType.Response:          
          setTimeout(() => {
            this.progress = 0;
            this.addPhotoMode = false;
          }, 1500);
      }
    });        
  }
  
  loadStoreUserPhotos() {
    this.accountService.getStoreUserPhotos(this.member.userId).subscribe((response: IPhoto[]) => {     
      this.photos = response;
    })
  }      

  initializeUploader() {
    this.uploader = new FileUploader({
      url: this.baseUrl + 'users/add-photo',
      authToken: 'Bearer ' + this.user.token,
      isHTML5: true,
      allowedFileType: ['image'],
      removeAfterUpload: true,
      autoUpload: false,
      maxFileSize: 10 * 1024 * 1024
    });
    
    this.uploader.onAfterAddingFile = (file) => {
      file.withCredentials = false;
    }    

    this.uploader.onSuccessItem = (item, response, status, headers) => {      
      if (response) {
        const photo: IPhoto = JSON.parse(response);        
        this.photos.push(photo);
        this.user.photoUrl = photo.photoUrl;            
      }
      *this.loadStoreUserPhotos();*
    }
  }

In the initializeUploader method, I had intended to include this.loadStoreUserPhotos() at the end to refresh all photos after uploading, including any newly uploaded ones. However, this line does not seem to have the desired effect, as users still need to manually refresh the browser.

Here is a simplified version of my HTML:

<div class="col-2"  *ngFor="let photo of photos">
        <img src="{{photo.photoUrl}}" alt="{{user.username}}" class="img-thumbnail" 
</div>

If anyone could offer assistance on this matter, it would be greatly appreciated! Thank you in advance!

Answer №1

After Aluan discovered that loadStoreUserPhotos() was not being executed, the solution I implemented was to include setTimeout(() => window.location.reload(), 2000) at the end of uploadFile(). Essentially, refreshing the current page resolved the issue. Adding a delay of 2 seconds allows users to read any warning or notification messages displayed on the screen.

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

What is a superior option to converting to a promise?

Imagine I am creating a function like the one below: async function foo(axe: Axe): Promise<Sword> { // ... } This function is designed to be utilized in this manner: async function bar() { // acquire an axe somehow ... const sword = await foo ...

Angular Universal functioning fine on local host, yet encountering issues on Nginx Server

I recently developed a project with Angular Universal. After building the project, it generated files such as browser, server, server.js, and prerender.js. I am curious to learn how I can run this project on an nginx server. Currently, I create a build o ...

Troubleshooting issues with ASP.NET bundling and minification when using Angular.js

After reviewing many questions on the same topic, none of them were able to solve my specific case. Our current challenge involves bundling and minifying AngularJs files within .Net code. The following code snippet shows how we are bundling our files insi ...

How to link a CSS file from a JavaScript file

I have a form for users with fields for first name, last name, password, and confirm password. I've implemented validation to check if the password and confirm password fields match using JavaScript: $(document).ready(function() { $("#addUser").cl ...

Utilizing the ng-if directive to choose the second element within an iteration of an ng-repeat loop

I am currently working on a project where I need to organize and group content by day. While the grouping function is working fine, I am facing an issue with treating the first two items in the loop differently from the rest. I have experimented with using ...

Python-based Routing in Azure Functions

Utilizing query parameters in Azure functions to retrieve values is possible "myfunction?p=one&p2=two" This question is what I am referring to How can I do Routing in Azure Functions? However, this only discusses C# and node.js. I am looking for ...

JavaScript / html Error: function body missing closing curly brace

I encountered an error that I'm struggling to resolve: "SyntaxError: missing } after function body". Despite not having a function named 'body', I have attempted changing every instance of 'body' in my script. However, ...

Make sure to verify if the mode in Angular is either visible-print or hidden-print

Here is a snippet of code <div class="row"> <div class="col-sm-12 visible-print"> Content (display in full width when printed) </div> <div class="col-sm-6 hidden-print"> Content (same as above but only half width when ...

Caution: PHP's move_uploaded_file() function is unable to successfully relocate the audio file

I've implemented a straightforward Record Wave script using Recorder.js Encountering an Issue Recording works fine Playback of my recording is successful Downloading the recorded file from blob works smoothly The problem arises when trying to uploa ...

Learn how to use sanitizer.bypassSecurityTrustStyle to apply styling to Pseudo Elements before and after in a template

Currently, I am attempting to add style to a pseudo element :after <a class="overflow">{{item?.eco}}</a> My goal is to modify the background color of a:after, and I believe this adjustment needs to be made in HTML. I've been thinking ...

What could be causing the block to fail in the event of an AJAX request?

I have encountered an issue with my PHP file and AJAX setup. The if block in my code is working properly, but the else block seems to be not functioning as expected. Even after changing the condition from data!= null to data== null, the problem persists wh ...

Implementing a feature in Typescript/React component that provides autocomplete functionality

Currently, I have developed a TypeScript and React component that has been published on NPM. My goal is to enable IntelliSense to autocomplete React props for this component. While I typically use JSDoc for plain React components, it does not seem to work ...

Difficulty encountered when converting objects into an array of a model within Angular

Below you will find the service code that I am using: export class ProductListService { constructor(private httpClient: HttpClient) { } getProducts(): Observable<IResponse> { return this.httpClient.get<IResponse>('https://local ...

Utilizing a parent scope variable in a callback function

This question delves more into the concept of JavaScript Closures rather than Firebase. The issue arises in the code snippet below, where the Firebase callback fails to recognize the variable myArr from the outer scope. function show_fb() { var myAr ...

Struggling with retrieving data from multiple models in backbone.js

I'm currently developing a node.js app using backbone but I'm facing some challenges in understanding how to fetch data from two related models. Specifically, I have models for Users and Comments, and on the user view, I need to display user info ...

Error in Typescript for a function that accepts several types of lists - property does not exist on the interface

In my project, I have defined three interfaces: a base interface and two others that extend the base one with children as properties. One of the interfaces includes 'valueType' while the other includes 'returnType'. Here is how they are ...

Exporting symbols within the same namespace from multiple files in a TypeScript project

I have a typescript module and I am looking to define symbols within the 'aaa' namespace from multiple files. Here is an example of what my code looks like: a.ts: export namespace aaa { export const a = "a"; } b.ts: export namespac ...

What is the best way to combine two JSON objects?

Item A: var item1 = { "roleid": "001", "techid": "001", "role": "WEB DEVELOPER", "tech": "JAVASCRIPT", "experience": [], "certifications": [], "gender": ["Male"], "awards": [], "min_experience_years": "4", "max_expe ...

Creating a Show/Hide toggle feature in AngularJS using NG-Repeat

I'm facing an issue with my code where I have a list of items that should only open one item at a time when clicked. However, currently, all items are opening on click and closing on the second click. Can anyone help me identify the problem in my code ...

Prevent pinch zoom in webkit (or electron)

Is there a way to prevent pinch zoom in an electron app? I've tried different methods, such as using event.preventDefault() on touchmove/mousemove events in JavaScript, adding meta viewport tags in HTML, adjusting -webkit-text-size-adjust in CSS, and ...