Check out myAngular article series with live demos

Using Angular Universal with Sql Server

Torgeir "Tor" Helgevold
- JavaScript Developer and Blogger
Published: Mon Jan 02 2017

In this post I will show how to use Angular Universal with Sql Server.

For the purposes of this post I have cloned the universal-starter, but replaced the simulated database with a real sql server database.

You can find my modified clone of the starter here.

The UI in the starter is already great, so most of my code changes involve adding a framework called Tedious to integrate node with sql-server.

The only other change is adding a table to display the result from my sql-server query.

I converted the UI to display a list of friends from my sql-server as seen below:

The starter project was already wired up with a promise against a simulated database. I simply swapped out the hard coded return value for the results of a sql query.

In the code below I am using the Tedious api to connect to the database and execute the query.

If you want to run this against your own database, just fill in the config object with your credentials and define a sql query.

export const realDataBase = { get() { return friendsQuery(); } }; function friendsQuery() { return new Promise(function(resolve, reject){ var Connection = require('tedious').Connection; var result = []; var config = { userName: 'userName', password: 'password', server: 'some-server' }; var connection = new Connection(config); connection.on('connect', function(err) { if (err) { console.log(err); } getFriends(); }); var Request = require('tedious').Request; function getFriends() { var request = new Request(`use your-database SELECT Id, FirstName, LastName FROM Friend`, function(err, rowCount) { if (err) { reject(err); } connection.close(); }); request.on('doneProc', function(rowCount, more) { resolve(result); }); request.on('row', function(columns) { let row = {}; columns.forEach(function(column) { row[column.metadata.colName] = column.value; }); result.push(row); }); connection.execSql(request); } }); }

All my database changes can be found in db.ts.

Next I made a tweak in home.component.ts to display the query result in table format:

<div class="home"> <h3>Friends</h3> <div class="table"> <div class="row header"> <div class="cell">Id</div> <div class="cell">First Name</div> <div class="cell">LastName</div> </div> <div class="row" *ngFor="let friend of data"> <div class="cell">{{friend.Id}}</div> <div class="cell">{{friend.FirstName}}</div> <div class="cell">{{friend.LastName}}</div> </div> </div> </div>

There you have it!

Angular Universal with Sql Integration.

If you liked this article, share it with your friends on social media:

We also have a new Facebook group about advanced Angular topics.

I invite you to follow me on twitter