简体   繁体   中英

How to get data from DB2 into an AngularJS application?

I want to create an AngularJS application where I need to get the data from a DB2 database.

How do I connect to DB2 directly from my AngularJS application? I couldn't find any references online.

Simple

  1. Create rest API endpoints to fetch data eg yourdomain/get/data in your DB2 server
  2. From your Angular app, make Ajax call to above end points

An AngularJS App doesn't directly connect to a DB2 database, it needs a server-side component to connect to the database.

Connect with any server-side framework to get a response from the database, for example PHP or node.js.

Here is an example to how to connect, I will be using PHP to get the server-side response.

In html:

<div ng-app="myApp" ng-controller="myCtrl">
<form>
     <button type="button" ng-click="getData()">GetResponse</button>
</form>
</div>

In AngularJS:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    $scope.getData = function () {
        $http({
            method: 'POST',
            url: "Path to Backend Handling File",
            data:{};
        }).then(function success(response) {
            console.log(response.data);
        }, function error(response){
        }
        });
    };
});

In PHP:

// This is an example code written in PHP
// Let $data will have response from database 
print_r(json_encode($data)); //used to return reponse to angular script used.
// Now response is stored in the response variable of success function as JSON which can be used as needed 

You need a server side component that talk to database and provides the data (eg json data) over http. The component can be written in your own language choice eg php, java etc. The angular shall talk to this API using Ajax calls and get the data that way.

AngularJS looks for some sort of REST (or REST-like) server to give it JSON results. In its default state DB2 requires some form of ODBC or JDBC driver to connect it into a programming language but it doesn't provide a REST-like interface.

Now that we've established this, let's look at a few ways you can solve your problem.

IBM offers some free DB2 User Defined Functions that speak REST and can be added to your instance. There is a download link contained in the linked article.

There is also an open source service from DreamFactory that does essentially the same thing - it drops a REST API in front of DB2.

I'd suggest that you investigate both options and see which one makes the most sense to you based on your requirements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM