Access this.nav from within FileUpload callback

Hi,

I’m new to Ionic/Angular JS, so please bear with me! :slight_smile: My app contains the following code, I’m trying to work out how to access the navigation from within a FileUpload callback…

constructor(nav, navParams, postsService) {
    this.nav = nav; // this.nav is defined here
    this.postsService = postsService;
    this.showOverlay = false;
  }

  newPost() {
    var options = {
      quality: 100,
      targetWidth: 600,
      targetHeight: 600,
      saveToPhotoAlbum: 0,
      destinationType: 1,
      allowEdit: true
    };

    Camera.getPicture(options).then((imageData) => {
      var options = new FileUploadOptions();
      options.fileKey = "file",
      options.fileName = imageData.substr(imageData.lastIndexOf('/') + 1);
      options.mimeType = "image/jpeg";
      options.params = {};

      var ft = new FileTransfer();
      ft.upload(imageData, encodeURI('https://myapp.com/data'), function(success) {
        this.nav.pop(); // This fails because this.nav is undefined
      }, function(error) {
        alert('Upload Failed');
      }, options);
    }, (error) => {
      alert('Error');
      alert(JSON.stringify(error));
      console.log(err);
    });
  }

Once the file transfer succeeds, I’d like to pop the current page off the navigation, but this.nav is undefined.

Can anyone suggest how I’d make it accessible in the callback?

Thanks!

because you are changing the context --> in every callback your are using “function () {}”.

Take a look in Camera.getPicture. Typescript introduced the “Fat-Arrow”-Syntax to keep the correct class-context on this.

So change your ft.upload callback to this syntax

ft.upload(imageData, encodeURI('https://myapp.com/data'), (success) =>  {
    this.nav.pop(); // This fails because this.nav is undefined
}, (error) => {
    alert('Upload Failed');
}, options);
1 Like

Thank you, that’s great!