How to connect to the API backend Angular.js

How to connect to the API backend Angular.js
Series “Developing applications on single-Angular.js”
  1. Why do I need Angular.js and why he
  2. Modern tools and framework Angular.js frontend applications
  3. Familiarity with controllers and directives Angular.js
  4. Writing Services in Angular.js
  5. Routing in Angular.js
  6. How to connect to the API backend Angular.js

In this article we will learn how to connect our application with a simple API using Restangular library. Restangular – a popular alternative to the built-in self Angular.js library for working with REST API. On its advantages over the standard library are well described on the project’s page at github: https://github.com/mgonto/restangular. For example, it supports all the HTTP methods and devoid of various nasty bugs embedded in Angular.js library.

As an API, we will use a small web application, written in the framework, of Sinatra, which is written in Ruby. You do not need to write ruby code. To run the API on your machine, perform the following steps:

  1. Install Ruby if you do not yet have. Online set of guidelines on this subject, including the official website https://www.ruby-lang.org/en/
  2. Download the app git clone https://github.com/mkdev-me/sinatra-api-example
  3. Go to the folder with the application and run bundle install
  4. Then run rake db:create db:migrate
  5. Finally, run the application command ruby app.rb

Done! Your little backend ready to go at localhost:4567. Now we can update Angular.js application to work with the API.

We have already connected Restangular step setup of our application: you can see it in the list of dependencies in a file bower.json. Moreover, the library is already loaded as a module, pay attention to the line in src/app/index.js :

angular.module('ngmkdev', ['restangular', 'ui.router', 'ui.bootstrap'])

Therefore, we can go directly to the code. First of all, we need to set the base URL, using which Restangular will build more links. To do this, the library has RestangularProvider provider that we can use in the config block in src/app/index.js :

// src/app/index.js
angular.module('ngmkdev', ['restangular', 'ui.router'])
.config(function ($stateProvider, $urlRouterProvider, RestangularProvider) {
RestangularProvider.setBaseUrl("http://localhost:4567");
< … >
});

The main reference for the default will be a link to the server with our API. Now update TransactionsStore so that it uses data from the server. Add two new methods: loadTransactions load all the data from the server, and addTransaction add a new transaction.

// src/components/transations_store.serve.js
angular.module('ngmkdev').factory('TransactionsStore', function(Restangular) {
return {
transactions: [],
loadTransactions: function() {
this.transactions = Restangular.all('transactions').getList().$object;
},
addTransaction: function(transaction) {
var that = this;
return Restangular.all('transactions').post({transaction: transaction}).then(function() {
that.transactions.push(transaction);
})
},
sum: function() {
var sum = 0;
this.transactions.forEach(function(el) {
sum += parseFloat(el.amount);
})
return sum;
}
}
});

Note the function then(). It is performed only when the completed request to add transaction. This mechanism is called the promises, which is an alternative for the usual jQuery callback mechanism. promise The difference is that we do not need to keep in mind when a callback is executed. Angular.js thus provides a guarantee that if the function A has finished its execution, the function B is executed (and only if the function A really well done).

In this case, we ensure that the array is updated only after the transaction is successfully saved a new transaction to the server. To reduce the number of server requests we will keep in memory all the transactions and update the array manually, instead of each time getting all transaction server.

Most Restangular functions return a promise-objects. For example, getList(), which we use for all transactions. To get yourself a transaction, we can either use then(), a method of $object, which immediately returns us all transactions.

Using the method of all(), we specify with some resource work. Restangular he guesses which links to send and receive data, provided that your application complies with REST API standards. Thus, post() will create a new record, get() will get a record, etc.

Controller code has not undergone major changes:

// src/app/main/transactions.controller.js
angular.module('ngmkdev').controller('TransactionsCtrl', function($scope, TransactionsStore) {
TransactionsStore.loadTransactions();
this.addTransaction = function() {
TransactionsStore.addTransaction(this.newTransaction);
this.resetTransaction();
}
this.resetTransaction = function() {
this.newTransaction = {
amount: 0.0,
date: "1993-02-01",
description: null
}
}
this.transactions = TransactionsStore.transactions;
this.resetTransaction();
});

Now all new transactions will be stored in the database and then reload the page, they will not be lost.

You probably created numerous test transactions to see how everything works. Now you have to be on them as something to get rid of. Commit to the changes: a0629f.

Homework:

  • Add and implement the delete button transaction.

This is the last article on Angular.js course. For 6 issues, we met with all the basic tools of modern frontend development and, following the best practices, a full written application running with the backend via the API. The knowledge gained will serve as an excellent foundation for writing more complex applications Angular.js. Write in the comments what you think about this series and how is your study and application Angular.js.

Related Posts

Leave a reply