Learn Multiple File Upload by building an Instragram-style app


#1

Hey all, it’s been a while since I’ve posted a tutorial, but it seems like I see multiple questions every week about uploading files. There’s really only one good way to do this, and I walk through it while building an Instragram-like app here: http://roblouie.com/article/574/learn-ionic-cordova-file-upload/

You can also directly grab the image upload server code here and the ionic app source here


Lazy loading and providers
#2

Nice!

I see u use async await a lot, almost on all methods. And u provide providers in the component, not main module

Any reason for this besides coding convenience?


#3

Definitely, the short one is the provider part. Per Angular best practices you should provide a service from the top most component where they will be shared. In this case the service is used only in this single component so that’s where it’s provided. Just modular code best practices, which helps greatly with reusability and with lazy loading (which based on their latest blog post Ionic is about to be much better at).

Regarding async/await, those are async calls so ultimately you have three choices: classic promises, promises with async/await, or Observables. I always favor readability in my code, so I default to async await unless I need some of the really cool features of Observables. Async await is an easy choice over the others because promise chaining and error handling reads exactly like synchronous code.

Consider the “uploadFromCamera” code block from my example, I could have written it with regular promises like this:

async uploadFromCamera() {
    this.uploadingSpinner.present();
    this.imageManagementService.uploadFromCamera())
      .then(() => this.loadImagePaths())
      .then(() => this.uploadingSpinner.dismiss())
      .catch(error => {
        this.uploadingSpinner.dismiss();
        console.log(error);
      });
}

And that’s totally fine, I could have even used Observables by using fromPromise on the second line and then using flatMap instead of then. However, I find using async/await to be much more readable:

async uploadFromCamera() {
  try {
    this.uploadingSpinner.present();
    await this.imageManagementService.uploadFromCamera();
    await this.loadImagePaths();
    this.uploadingSpinner.dismiss();
  } catch(error) {
    this.uploadingSpinner.dismiss();
    console.log(error);
  }
}

Edit: Changed my promise vs async example to a different code block that I thought better illustrated the point


#4

check this answer and let me know if it works for you https://stackoverflow.com/a/53865602/4540048