The Observable constructor in Nativescript must be called with the 'new' keyword in order to be invoked

I am facing a challenge while attempting to upload a multipart form in nativescript using http-background. The error message "Class constructor Observable cannot be invoked without 'new'" keeps appearing. I have tried changing the compilerOptions target to es5 and es2017, but it did not resolve the issue.

https://i.sstatic.net/1llMX.png

Below is the code snippet from the component:

  onSave(){
    console.log("clicked")
    this.proccessImageUpload(this.file);
  }

public onSelectSingleTap() {
  this.isSingleMode = true;
  
  let context = imagepicker.create({
      mode: "single"
  });
  this.startSelection(context);
}

private startSelection(context) {
  let that = this;

  context
  .authorize()
  .then(() => {
      that.imageAssets = [];
      that.imageSrc = null;
      return context.present();
  })
  .then((selection) => {
     console.log("Selection done: " + JSON.stringify(selection));
     this.file = selection[0]._android;    
    
     
     
    
      that.imageSrc = that.isSingleMode && selection.length > 0 ? selection[0] : null;

      // set the images to be loaded from the assets with optimal sizes (optimize memory usage)
      selection.forEach(function (element) {
          element.options.width = that.isSingleMode ? that.previewSize : that.thumbSize;
          element.options.height = that.isSingleMode ? that.previewSize : that.thumbSize;
      });

      that.imageAssets = selection;
  }).catch(function (e) {
      console.log(e);
  });
}

proccessImageUpload(fileUri) {
  var backgroundHttp  = require("nativescript-background-http");
  return new Promise((resolve, reject) => {
      
      var request = {
          url: 'http://192.168.0.2:4000/api/posts',
          method: "POST",
          headers: {
              "Content-Type": "application/octet-stream",
              "user_id": "<user_id>"
          },
          description: 'Uploading profile image..',
          androidAutoDeleteAfterUpload: false,
          androidNotificationTitle: 'Profile image'
      }

      var params = [
        { name: "title", value: "test" },
        { name: "content", value: "test" },
        { name: "fileToUpload", filename: fileUri, mimeType: "image/jpeg" }
     ];

     var backgroundSession = backgroundHttp.session('image-upload');
     var task = backgroundSession.uploadFile(fileUri, request);

      task.on("progress", (e) => {
          console.log(`uploading... ${e.currentBytes} / ${e.totalBytes}`);
      });

      task.on("error", (e) => {
          console.log(`Error processing upload ${e.responseCode} code.`);
          reject(`Error uploading image!`);
      });

      task.on("responded", (e) => {
          console.log(`received ${e.responseCode} code. Server sent: ${e.data}`);
      });

      task.on("complete", (e) => {
          console.log(`upload complete!`);
          console.log(`received ${e.responseCode} code`);
      })

      resolve(task);
  });
}

The problem seems to be originating from this particular line of code:

var task = backgroundSession.uploadFile(fileUri, request);

Any assistance on resolving this issue would be highly appreciated!

Answer №1

To resolve the issue, make sure you are using the latest version of the nativescript-background-http plugin.

If not, you can update to the latest version by running the following command:

tns plugin add @nativescript/background-http

Answer №2

After installing tns version 6, I successfully managed to make it work.

Answer №3

I encountered a similar issue and found the solution on Slack from Chris Vietor's recommendation. To address this problem, use the command "tns plugin add nativescript-background-http" for Nativescript 6 or use "tns plugin add @nativescript/background-http" for Nativescript 7.

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

"Here's a comprehensive guide on how to connect dynamic data with angular-tree-grid components

ERROR TypeError: Cannot read property 'map' of undefined Can anyone help with binding dynamic data? I'm currently using angular-tree-grid but struggling to bind dynamic data. <html> <db-angular-tree-grid (expand)= ...

What is the process of creating an instance of a class based on a string in Typescript?

Can someone please guide me on how to create an instance of a class based on a string in Nestjs and Typescript? After conducting some research, I attempted the following code but encountered an error where it says "WINDOWS is not defined." let paul:string ...

The new mui v5 Dialog is having trouble accepting custom styled widths

I am facing an issue with my MUI v5 dialog where I cannot seem to set its width using the style() component. import { Dialog, DialogContent, DialogTitle, Paper, Typography, } from "@mui/material"; import { Close } from "@mui/icons- ...

What is the best way to switch the CSS class of a single element with a click in Angular 2

When I receive data from an API, I am showcasing specific items for female and male age groups on a webpage using the code snippet below: <ng-container *ngFor="let event of day.availableEvents"> {{ event.name }} <br> <n ...

Using type definitions in non-TS files with VSCode: A beginner's guide

My code is not in TypeScript, shown here: // foo.js module.exports = app => { // some logic here } I want to enhance my development experience by using TypeScript definition files to specify the type of the argument app, enabling VSCode to provide ...

Preserve information across different AngularJS views using vs-google-autocomplete

Currently, I am in the process of developing my inaugural Angular Application, which enables users to sift through a database of vendors using various criteria. One such criterion is the vendor's location and the distance from the user. In order to t ...

Creating formGroups dynamically within an ngFor loop inside an accordion

I am facing a challenge with an accordion feature that generates a specified number of sections x based on user input. Here is an example: https://i.sstatic.net/QjmkW.png After creating the sections, I need to load employee information into each section ...

Protractor Browser Instance Failure

We have encountered an issue with our UI suite failing in Chrome during the login process. Initially, we thought it might be due to upgrading to Chrome 79, as the problems arose simultaneously. Interestingly, the login functionality still works smoothly in ...

Issue with Nodemon and Typescript causing errors with Worker Threads

Currently, I am in the process of integrating a worker thread into my Typescript and node.js application. Let's take a look at my thread.ts file: import { Worker, isMainThread, parentPort, workerData } from "worker_threads"; let thread ...

Loading an external template on the fly in AngularJS

As I work on creating a customizable table component in AngularJS, my goal is to have rows become editable when the user clicks an "Edit" button. The edited row should then display an input form bound to the model. To see my progress so far, you can check ...

Strange occurrences observed while looping through an enum in TypeScript

Just now, I came across this issue while attempting to loop through an enum. Imagine you have the following: enum Gender { Male = 1, Female = 2 } If you write: for (let gender in Gender) { console.log(gender) } You will notice that it iter ...

Problem with the property `className` not adding correctly on `$scope.eventSource`

Currently, I am utilizing the AngularJS directive to integrate the Arshaw FullCalendar. However, I am encountering an issue where the className specified in $scope.eventSource is not appearing on the event object. Here is a snippet of my code: $scope.even ...

Is there a method in AngularJS to have $http.post send request parameters rather than JSON?

I have come across some older code that utilizes an AJAX POST request using jQuery's post method. The code looks something like this: $.post("/foo/bar", requestData, function(responseData) { //do stuff with response } The request ...

Dollar Sign vs "$$()" Sparkling Protractor with "by.css()" vs "$()"

I'm a bit confused about the purposes of the $ and $$ commands. I initially thought they were just substitutes for 'by.css', but why use $$? <element id = "eId"></element> Based on the example above, I assumed that these two l ...

How can Material UI Textfield be configured to only accept a certain time format (hh:mm:ss)?

Looking for a way to customize my material ui textfield to allow input in the format of hh:mm:ss. I want to be able to adjust the numbers for hours, minutes, and seconds while keeping the colons automatic. Any suggestions would be welcomed. ...

Optimal methods for organizing various perspectives on a one-page website

I am developing an application that incorporates AngularJS and Bootstrap. The current setup involves organizing various views using ng-show, allowing for view changes based on button interactions and the enablement/disabling of ng-show values. Within a si ...

Is there a way to dynamically define the return type of a function in Typescript?

Can the variable baz be dynamically assigned the string type? type sampleType = () => ReturnType<sampleType>; // Want to return the type of any function I pass (Eg. ReturnType<typeof foo>) interface ISampleInterface { baz: sampleType; } ...

Ways to address a buffered data problem in Websocket Rxjs. When trying to send a message, it is not being received by the server and instead is being stored in a

Currently, I am utilizing Websocket Rxjs within my application. The connection is successfully established with the server, and upon subscribing to it, all data is received in an array format. However, when attempting to send data back to the server, it se ...

Blend the power of Node's CommonJS with the versatility of Typescript's ES modules

I currently have a Node.js v10 legacy application that was built using CommonJS modules (require). The entire codebase is written in JavaScript. However, I am considering upgrading the app and refactoring a specific part of it to use TypeScript modules ( ...

Exploring the functions of the elasticsearch javascript library: Understanding the search_type feature

Currently, I am attempting to run a search query using search_type of count with the elasticsearch.angular.js version sourced from the npm module. The query can be successfully executed as follows: POST /index1/type1/_search?search_type=count { " ...