3 Ways to Ensure Your Picture Uploads are Visible Right Away

I am currently working on an Ionic app that enables users to upload images to Firebase storage. One issue I am encountering is that the image only changes once a new one is selected, after closing and reopening the app. I would like it to update immediately upon uploading, and revert back to a placeholder image as soon as it's deleted.

Although the functionality is there, the uploaded image is only visible after closing and reopening the page.

TypeScript:

    constructor(private router: Router,
              private authService: AuthService,
              private imageService: ImageService,
              private afAuth: AngularFireAuth) {

      this.afAuth.authState.subscribe(user => {
      this.userId = user.uid
      console.log('constructoruser', this.userId);
      });
              }

  ngOnInit() {
          this.firestore.ref(`/Photos/${ this.userId }/`).child('photo0').getDownloadURL().then((url) => {
          this.photo0 = url;
        }).catch((error) => {
          console.log(error.message);
          this.photo0 = 'assets/img/add-an-image.png';
          console.log(this.photo0);
        });
  }

HTML:

<div>
    <img [src]="photo0" (click)="UploadPic0('photo0')"/>
</div>   

Answer №1

After analyzing the code snippet you provided (excluding the UploadPic0 method), it appears that the issue is occurring because the image is being set from the URL only once during component initialization (specifically in ngOnInit, which runs only once).

To address this issue, consider the following solution:
- Develop a new method to update the image (either with the image URL or a fallback image)
- Invoke this method in ngOnInit and whenever there is a success/failure message related to image upload
- As an additional measure (to ensure that the render method is executed once the image is updated), trigger the change detector.

Here's an example:

updateImage() {
        this.firestore.ref(`/Photos/${this.userId}/`).child('photo0').getDownloadURL().then((url) => {
         this.photo0 = url;
        }).catch((error) => {
          console.log(error.message);
          this.photo0 = 'assets/img/add-an-image.png';
        });
}

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

How to integrate custom plugins like Appsee or UXCAM into your Ionic 2 application

Struggling to integrate either Appsee or UXcam into my project. I attempted to import the plugin like this, but it didn't work: // import { Appsee } from '@ionic-native/appsee'; I read somewhere that you need to declare the variable for Ty ...

Using webpack to bundle node_modules into your application

I am facing an issue while trying to load some modules like: moment echarts In my package.json file, I have the following versions specified: "echarts": "^3.1.10" "moment": "^2.14.1" However, I am encountering the errors below: VM2282:1 Uncaught Ref ...

What is the significance of using the @Input decorator on a component property in Angular?

Within this particular component, I discovered the @Input decorator connected to the variable. @Input() description: string; The variable "description" is then utilized in the HTML as an interpolation. <div>{{description}}</div> This prompt ...

Exploring the integration of LeafLet into Next JS 13 for interactive mapping

I'm currently working on integrating a LeafLet map component into my Next JS 13.0.1 project, but I'm facing an issue with the rendering of the map component. Upon the initial loading of the map component, I encountered this error: ReferenceError ...

Is jest the ideal tool for testing an Angular Library?

I am currently testing an Angular 9 library using Jest. I have added the necessary dependencies for Jest and Typescript in my local library's package.json as shown below: "devDependencies": { "@types/jest": "^25.1.3", "jest": "^25.1.0", ...

"Enhancing User Experience: Implementing Internationalization and Nested Layouts in Next.js 13.x

In the midst of working on a cutting-edge Next.js 13 project that utilizes the new /app folder routing, I am delving into the realm of setting up internationalization. Within my project's structure, it is organized as follows: https://i.stack.imgur.c ...

Tips for triggering multiple components in Angular2 with a single event

My current project involves an input component, an output component, and a processing service. The goal is to allow the user to input a string, have it processed by the processing service, and then display the processed message in the output component. How ...

Guide on creating a Typescript function with a strongly typed argument

I am looking to develop a function that accepts a type created using export class and imported in the traditional manner as an extension of a particular type. With a base Page class and various derived classes, I aim to have this function capable of receiv ...

Is it not possible to call this authentication expression in a Typescript file when using Next JS?

I am currently developing a sign-in method for my Next.js application and I have been referring to the GitHub repository's recommended documentation. However, upon reaching the authentication folder step, I encountered an error regarding the sign-in ...

Is there a way to transmit the wellness update of my Angular application to Akamai?

I currently have an Angular application and am utilizing the Akamai CDN. Can you advise me on the most effective method to relay the health status (200, 500, etc.) to Akamai? I want to ensure that in case it doesn't return a 200 code, Akamai is able t ...

What is the process for sending a post request in Ionic 2 to a Node server running on localhost?

When working with Ionic, I utilized a service provider to access HTTP resources. The Service.ts file looks something like this. Here, data is represented as a JSON object. import { Injectable } from '@angular/core'; import { Http, Headers } fro ...

Encountered an error while attempting to update an object: Unable to read property 'push' of undefined

Encountering an issue while attempting to update an object with additional information, receiving an error message stating 'property \'push\' of undefined'. /*Below is the object model in question:*/ export class Students { ...

Turn off the interconnected route while utilizing npm to display the tree of dependencies

If I want to display the project's dependencies tree using npm, I would use the following command: npm ls lodash The output will look something like this: > npm ls lodash npm info using [email protected] npm info using [email protected] ...

Execute tap() function without subscribing

Can the tap() pipe function be executed without subscribing to it? observer$:BehaviorSubject<number[]> = new BehaviorSubject<number[]>([1]) getData(page:number):void{ of(page).pipe( tap({ next: (data) => this.observe ...

Having difficulty integrating requireJS and Node's Require in a single TypeScript project

I currently have a TypeScript project that is intended to work with both Node and the browser. In some scripts, I'm utilizing Node's require(), while in others requireJS's require(). The structure of my project directory is as follows: myPr ...

Using forkJoin() to introduce a delay between asynchronous API calls

Here is the code snippet I am currently working with: return forkJoin( pages.map( i => this.http.get(`devices?page=${i}&size=8000`) ) ).subscribe((event: any) => { event.forEach((entry) => { ...

The value of a checkbox in Angular 10 is coming out as undefined

Within my component, I set up the formGroup as shown below: constructor(private apiService: ApiService) { this.form = new FormGroup({ product: new FormControl(), shops: new FormGroup({}) }); } When selecting a vendor from a drop-do ...

Different parameters in an Angular filter pipe

Currently, I am facing a challenge in implementing multiple filters on a pipe for a search result page that retrieves data from an API. How can I integrate different parameters into this filter pipe successfully? Access the application here: https://stack ...

Assign variable data to properties within an immutable object within a React component

I have declared a Const in my config.service.ts file like this: export const mysettings={ userid:"12324", conf:{ sessionDuration:30, mac:"LON124" } } I am using this constant in various components. However, instead of hardcoding these val ...

Is there a way to fetch a particular object from Firebase database based on its value using AngularFire2?

Here is the database I am working with: firebase database I am trying to retrieve a dish that has its 'featured' attribute set to true (dish.feature = true). Is it possible to do this directly from the database, or do I have to retrieve all di ...