How to send data using http post request to server using NativeScript ? - SpartaCode

SpartaCode

Make your development faster and easier !

How to send data using http post request to server using NativeScript ?


What is NativeScript ?
NativeScript is Open Source framework for building truly native mobile apps using Angular, TypeScript or JavaScript.
NativeScript currently supports apps for Android and IOS platforms.
Its is easy to learn, provides good support to easily accessing Native API's both in Android and IOS.
I consider you have installed Nativescript Successfully.

Lets get started,

Step 1: Create Project 
To create Nativescript project type following code into your terminal or cmd(Command Prompt)

tns create PostRequest --template nativescript-template-ng-tutorial
You can also create CreateProject.bat file to use it each time you create project :
set /p input="Enter Project Name : "

tns create %input% --template nativescript-template-ng-tutorial

pause

Step 2: Import Http Module
After creating project open project in Visual Studio Code(Editor with good support for nativescript).
Go to app->app.module.ts file add following code in imports :
import { NativeScriptHttpModule } from "nativescript-angular";

Also add to Module imports as shown here :

Step 3: Add http utility file to your Project 
To perform http post request to server from nativescript application you can use this utility file which will save your time.
Place this file into services folder for better arrangement of folder structure :
Go to your Nativescript Project and create new file into services folder named user.services.ts
Copy paste following code :

import { Injectable } from "@angular/core";
import { Http, Headers, Response, RequestOptions } from "@angular/http";
import { Observable as RxObservable } from "rxjs/Observable";
import "rxjs/add/operator/map";

@Injectable()
export class UserService {

  // private serverUrl = "https://httpbin.org/post";
  constructor(private http: Http) {}
  postData(data: any)
  {
    let options = this.createRequestOptions();
        return this.http.post("http://IPAddress/XamppProject/testRequest.php",{ data } , options)
            .map(res =>  res.json());
  }

   private createRequestOptions() {
        let headers = new Headers();
        headers.append("AuthKey", "my-key");
        headers.append("AuthToken", "my-token");
        headers.append("Content-Type", "application/json");
        let options = new RequestOptions({ headers: headers });
        return options;
    }
}

Step 4: Using utility file to send post request to server
Finally we will use the utility file and send post request to server. You can import UserService class into any component of your application, for now we will import it in app.component.ts file.
In app->app.component.ts import the UserService class we just created in step 3.
import { UserService } from "./services/user.service";

Include UserService as Providers in component as shown here :

In the image :
1 : Import UserService which is exported class.
2 : Include UserService as Provider to this Component.
3 : Perform Post request to specified Server.
To perform post request insert this code in app.component.ts as shown above :
    userService.postData({LeaderId:"1"}).subscribe((res) => {
      alert(res);
    }, 
    (err)=>console.log("Something went wrong "+err)
    );

So here we complete application side coding. Now lets create PHP file on Server to get data sent from NativeScript Application.
Just add following code in testRequest.php file created on server xampp Project(http://localhost/MyProject/testRequest.php)
 $data = file_get_contents("php://input");
 echo json_encode($data);

Run Project by entering this command in terminal/cmd :
Android :
tns run android
IOS :
tns run ios

Now, just go ahead and test your project and leave some comments and share my post.

Get all files of project here :  GitHub Link

No comments:

Post a Comment

News

Get Amazing Traffic to your Site

Traffic Exchange

Post Bottom Ad

Responsive Ads Here