Top

Node API to get data from SQL Server for Angular 2 web application

With the full stack technologies i.e. MEAN (Mongo DB, Express JS, Angular2, Node JS), Mongo DB is a default option we consider for the database. However, we had a task to revamp some of the pages of the existing web application using Angular2 and Node JS. The existing application was developed using .Net Web forms and SQL Server. So, we didn’t have choice but to use existing SQL server instead of Mongo DB.

This blog describes the steps to install sql server package through npm and to develop a web application using Node JS, Angular2 and Express JS.

Note that the basic knowledge of Angular 2, NodeJS, ExpressJS and SQL Server is a must as a prerequisite to follow the steps mentioned in this blog. Also, installation of NPM and Angular CLI is assumed to be already done. To know more about how to install please refer this site https://angular.io/guide/quickstart:

Get started with the development

First of all, we will need “mssql” package to connect our node server with the SQL server database.

To download it, go to the project directory and run this command:

npm install mssql –save

Npm will download the required files from the packages and also it will update package.json file

Add (require) packages in server.js file

const sql = require(‘mssql’);

//write the configuration to connect to our database:

var config = {

 user: ‘username’,

 password: ‘password’,

 server: ‘your-server-name’,

 database: ‘database-name’

 };

Connect To Database

sql.connect(config, function(err) {

 if (err) { console.log(‘Connect err: ‘ + err); return; }

 isConnected = true;

});

If all the config data is correctly set, connection to the database will be successful, otherwise it will log the error in the browser console.

Query execution

To execute two or more queries in a single API call, we will use callback and async library.

To know more about async visit this site: https://caolan.github.io/async/

We will create a stack of two functions and will write our query in each function.

//function 1

var firstquery = function(callback) {

 var request = new sql.Request();

 request.query(“your-first-sql-query-here”, function(err, result){

if (err) console.log(err);

callback(err, result);

 });

}

//function 2

var secondquery = function(callback) {

 var request = new sql.Request();

 request.query(“your-second-sql-query-here”, function(err, result){

if (err) console.log(err);

callback(err, result);

 });

}

Create  stack and push both the function in it

var stack = [];

stack.push(firstquery);

stack.push(secondquery);

//write your api function now

API Call

app.post(‘your-api-path’, function(req, res) {

   async.parallel(stack, function(err, results) {

if (err) {    

 console.log(“error occurred”, err);

 res.send({

       “status”: 400,

       “error”:”error occurred”

 })

}

  else {

  //send response as json  

      res.status(200).json(results);

}

 });

});

With the above code, we will be able to run two sql queries on a single API call and to send final JSON result in the response.

Get data from API in Angular 2

We will need to use HTTP module from @angular/http library.

To call our Node API, we need to create a service file and import required modules from @angular library.

//service file

import { Injectable } from ‘@angular/core’;

import { Http, Response, Headers } from ‘@angular/http’;

import { Observable } from ‘rxjs/Observable’;

import ‘rxjs/add/operator/map’;

@Injectable()

export class ServiceName {

 constructor(private http: Http) { }

 functionName() {

return this.http.get(‘your-api-url’)

 .map(res => { res.json()

   // console.log(“I CAN SEE DATA HERE: “, res.json());

   return res.json();

 });

 }

}

//component file

Import our service file in component file

import { ServiceName } from ‘path-of-file’;

//Now write service instance in constructor and call our service

export class AppComponent {

   constructor(private instanceName: ServiceName) { }

functionName() {

   this.instanceName.functionName().subscribe(

   res => { console.log(“See data here” + res)  }

)

}

}

Here we have got the data from Node API which can be used to display data in a predefined HTML view.

Hire US