Make an http.patch request to the server using a Nativescript application

I am attempting to make an http.patch request to the server in my Nativescript application, which is built with Typescript and Angular2. The backend system is developed using Python(Django).

Here is the code for my request:

  updateOrder(id, message) {
  let headers = new Headers();
  headers.append("Authorization", "Token " + Config.token);
  headers.append("Content-Type", "application/json");
  return this.http.patch(
      Config.apiUrl + "orders/" + id + "/",
      message,
      {headers: headers}
  )
  .map(response => response.json())
  .catch((res: Response) => this.handleErrors(res));

Next, I execute the request:

changeStatus(status){
    var message = JSON.stringify({status: status});
    this.orderService.updateOrder(this.order.id, message).subscribe(
        data => console.log(data),
        err => alert(JSON.stringify(err))
    );
}

However, the server responds with the following data:

{"_body":{},"status":200,"ok":true,"statusText":"","headers":{},"type":3,"url":null}

Despite this response, the "status" property that I intended to change remains unchanged.

What could be causing this issue?

Answer №1

Utilize the http module available in NativeScript.

To send a PATCH request, you can refer to the following example:

In your page.ts file (TypeScript example):

  import * as http from"http";
  http.request({
      url: "https://httpbin.org/patch",
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      content: JSON.stringify({ MyVariableOne: "ValueOne", MyVariableTwo: "ValueTwo" })
  }).then(response => {
      var result = response.content.toJSON();
      console.log(result);
  });
}

For more information on the HTTP module, check out the API reference here: https://docs.nativescript.org/api-reference/modules/http.html

Additionally, you can find a detailed documentation article on how to post JSON data using HTTP requests here:

Answer №2

Here is my approach to handling http requests:

1.- Begin by including the NativeScript http module in the Root App NgModule:

import { NativeScriptHttpModule } from "nativescript-angular/http";
...
@NgModule({
  imports: [
      ...
      NativeScriptHttpModule,
      ...
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})

2.- Next, import Angular's http (and headers if necessary) into your component:

import { Http, Headers } from '@angular/http';

3.- Inject the imported module in the constructor:

constructor(private http: Http, ...) { ... }

4.- Utilize the http methods (such as POST in this example, but adaptable for any):

var url = "http://www.api-url.com/example.php";
var body = {foo: "foo", bar:"bar"};
let headers = new Headers();
headers.append("Authorization", token); //You can include any required headers
headers.append("Content-Type", "application/json");
this.http.post(url, body, { headers: headers })
    .map(res => res.json())
    .subscribe(
        data => this.connectionEstablished(data),
        err => this.handleErrors(err)
    );

If encountering an error with the map() method, remember to add the following line:

import "rxjs/add/operator/map";

I trust this information proves beneficial!

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

Disguising the Navigation Bar when choosing from various databases

I am currently facing the following issue: <div class="container"> <h3 class="d-flex justify-content-center">Database</h3> <div class="row"> <div class="col-xs-12"> < ...

Is it possible for Angular 2 JWT to have an unauthenticatedRedirector feature?

Having transitioned from Angular 1 where JWT tokens were used for user authentication, I had the following code: .config(function Config($httpProvider, jwtOptionsProvider) { // Interceptor to add token to every $http request jwtOptionsProv ...

JavaScript - Trouble encountered while trying to use splice to insert one array into another array

I've been working on creating a Cache Hashtable using JavaScript. When I use the code cache.splice(0,0, ...dataPage);, it inserts my data starting from the first position up to the length of dataPage. Assuming that my dataPage size is always 10. Th ...

"An error occurred while trying to resolve "npm" from npm.fontawesome.com

Within my Angular project, I am utilizing a module from When I run the following command: npm --loglevel info install grun locally, it finishes without any issues. However, when I run this command on the build server, an error occurs. In my .npmrc file: ...

Implementing Angular *ngFor to Reference an Object Using Its Key

myjson is a collection of various hijabs and headscarves: [ { "support": 2, "items": [ [ { "title": "Segitiga Wolfis", "price": 23000, "descripti ...

The dynamic concatenation of Tailwind classes is failing to have any effect, even though the full class name is being

I'm currently using Tailwind CSS within my Next.js project and I have a common method that dynamically returns the desired background color. However, despite adding the full class name, the background color is not displaying as expected. After reading ...

Attempting to launch Angular application on GitHub Pages

I need help deploying my Angular application on GitHub pages using node.js 14.20.0. I've successfully installed: npm i angular-cli-ghpages However, when I try to run : ng deploy --base-href=https://rejkid.com.github.io/ScheduleMeFrontEnd/ as recomme ...

When attempting to import a react component written with TypeScript to npm, receiving an 'undefined' error

I recently encountered an issue when trying to publish my custom React component developed with TypeScript on npm. Although the publishing process was successful, I faced an error upon importing the npm package into a new React project: Error: Element ty ...

Tips for executing embedded scripts within templates

I am using a controller to display the Instagram embedded code <div class="instagram_here" [innerHtml]="instagram_embeded_code"></div> However, it is only showing a blank Instagram block. https://i.stack.imgur.com/gNPDL.png I suspect there m ...

Reattempting a Promise in Typescript when encountering an error

I am currently working on a nodeJS application that utilizes the mssql driver to communicate with my SQL database. My goal is to have a unified function for retrieving a value from the database. However, in the scenario where the table does not exist upon ...

How to access properties of objects within an array in Angular 4

Is there a method to call only the $values from each rate record in my array that I want to read? https://i.sstatic.net/MT2XK.png This is what I have done to access this array: async ngOnInit() { this.product$ = await this.reviewService.getReview(th ...

What method can be utilized to selectively specify the data type to be used in TypeScript?

Currently, I am facing a scenario where a certain value can potentially return either a string or an object. The structure of the interface is outlined as follows: interface RoutesType { projects: string | { all: string; favorite: string; cr ...

The manager encountered an issue while querying for "Photo" data: EntityMetadataNotFoundError - no metadata could be found

I encountered an error while attempting to utilize typeorm on express: if (!metadata) throw new EntityMetadataNotFoundError(target) ^ EntityMetadataNotFoundError: Unable to locate metadata for "Photo". Below is my data source: import " ...

Is it possible to share screens via socket.io without the need for selecting a screen prompt?

I am looking to select my screen and share it on a socket.io server without any pop-up form the browser using navigator.mediaDevices.getDisplayMedia({ video: true }).then((stream: MediaStream) => { ...

Divide a list Observable into two parts

In my code, I have an Observable called 'allItems$' which fetches an array of Items. The Items[] array looks something like this: [false, false, true, false] My goal is to split the 'allItems$' Observable into two separate Observables ...

What steps can be taken to stop Internet Explorer from caching Ajax requests in Angular2 using TypeScript?

Imagine a situation where a user has 10 points. When they click a button, an ajax call is made to the server to update the user's points after they have been used. The server should send back 9 points, which is functioning correctly on all browsers ex ...

Invoke a function of a child component that resides within the <ng-content> tag of its parent component

Check out the Plunkr to see what I'm working on. I have a dynamic tab control where each tab contains a component that extends from a 'Delay-load' component. The goal is for the user to click on a tab and then trigger the 'loadData&apo ...

Guide to building an interface for an object containing a nested array

While working on my Angular/TypeScript project, I encountered a challenge in processing a GET request to retrieve objects from an integration account. Here is a snippet of the response data: { "value": [ { "properties": { ...

Typescript: Transforming generic types into concrete types

I am utilizing a Generic type type GenericType = { [key: string]: { prop1: string, prop2?: string, prop3?: number, }, }; The purpose of the Generic type is to assist in constructing / validating a new object that I have created. const NewO ...

SmartEdit functions properly when spartacus is running using yarn start --ssl, but does not work without SSL enabled

I followed the smartedit setup instructions at and everything works well when I start the Spartacus server with yarn start --ssl. However, if I start the server with just yarn start, the storefront does not appear. See image here for reference ...