Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Data Oriented Development with Angularjs
Data Oriented Development with Angularjs

Data Oriented Development with Angularjs:

eBook
€14.99 €16.99
Paperback
€20.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Data Oriented Development with Angularjs

Chapter 2. Working with Data

Now that we've already covered the basics of AngularJS and data binding, let's take a deep dive into Angular and see what dependency injection is, why it is needed, and how to do dependency injection in Angular. We'll also see the role of filters and how to write custom filters. Then, we'll see how to call remote APIs using the $http service and the $resource service. Finally, we'll study how the $resource service is an abstraction on top of the $http service and how it makes communication with RESTful APIs easier. So, let's get started.

In this chapter, we will cover the following topics:

  • Dependency injection and why it is needed
  • How dependency injection is achieved in Angular
  • The role of filters and how to implement them
  • What are promises?
  • How to communicate with backend APIs using the $http service
  • How the $resource service makes communication with RESTful services easier

Dependency injection

The dependency injection pattern, as the name suggests, is the process of injecting dependencies (or services) into another (client) object. It is also referred to as Inversion of Control (IoC). Without it, a client has to create instances of dependent objects itself, whereas with dependency injection, these objects are handed to the client by someone else (typically, an IoC container). This is commonly referred to as the Hollywood principle—"don't call us, we'll call you". The following is an example C# code to make things more clear:

public interface IShippingService {
  double CalculateShippingCost ();
}

public class ShippingService : IShippingService {
  double CalculateShippingCost () {
    // do some lengthy calculation here and
    // calculate the shipping cost
  }
}

public class LoggingShippingService : IShippingService {
  double CalculateShippingCost () {
    // do some lengthy calculation here and
    // calculate the shipping...

Filters

It often happens that we need to show filtered data. In this case, we can include logic in one of the functions in a service. However, this logic can get lost if a service has many methods. Similarly, we might have to format some data before showing it in the view. Angular introduces filters for precisely these things—either format the value of an expression for display or filter values from an array. Angular comes with some of the most common filters to format number, currency, or date. Refer to the built-in filters available at https://docs.angularjs.org/api/ng/filter.

Let's write a custom filter. In our previous example, our service returns some employees. Let's add a few more employees whose age is more than 58 years. Let's assume that the retirement age is 60 years, and anyone whose age is 58 years or more is about to retire. Then, let's filter the employees. So, here's the modified service:

'use strict';

app.service('employeeSvc...

Promise

While working with Angular/JavaScript, or any technology for that matter, there are scenarios when we need to make asynchronous calls—a very common example is of calling a web API. Obviously, when we call a remote API, we can't call it synchronously, because all further processing stops until that call completes. One of the ways of calling a function asynchronously is using a callback. However, callbacks make the code look convoluted. Sometimes, if you have deeply nested callbacks, then life becomes even more difficult. Promises solve these issues and make the intent of the code very clear. The Promise API is part of the ECMAScript 6 (ES6 Harmony) proposal, but there are implementations of it, which we can use even now.

A Promise object (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) is used for deferred and asynchronous computations. A Promise object is in one of the following states:

  • Pending: This is an initial state, not fulfilled...

The $q service

The $q service of Angular is modelled on the lines of ES6 promises, though not all of the supporting methods from ES6 Harmony promises are available yet. Check out the documentation of the $q service for more details at https://docs.angularjs.org/api/ng/service/$q.

The $http service

The $http service is a core Angular service. This service is used to communicate with remote HTTP servers via the browser's XMLHttpRequest object or JSONP. The $http API is based on the promise APIs exposed by the $q service. This service, unsurprisingly, exposes methods that reflect the HTTP verb names, get, head, post, put, delete, and so on. The typical way of calling these methods is as follows:

$http.get('/someUrl')
    .success(function(data, status, headers, config) {
      // this callback is called asynchronously
      // when the response is available
    })
    .error(function (data, status, headers, config) {
      // called asynchronously if an error occurs
      // or server returns response with an error status
    });

So, let's see an example of using the $http service. Postcodes.io is a free and open source postcode and Geolocation API for the UK. It exposes many API endpoints. We'll specifically use the one that gives us information...

Dependency injection


The dependency injection pattern, as the name suggests, is the process of injecting dependencies (or services) into another (client) object. It is also referred to as Inversion of Control (IoC). Without it, a client has to create instances of dependent objects itself, whereas with dependency injection, these objects are handed to the client by someone else (typically, an IoC container). This is commonly referred to as the Hollywood principle—"don't call us, we'll call you". The following is an example C# code to make things more clear:

public interface IShippingService {
  double CalculateShippingCost ();
}

public class ShippingService : IShippingService {
  double CalculateShippingCost () {
    // do some lengthy calculation here and
    // calculate the shipping cost
  }
}

public class LoggingShippingService : IShippingService {
  double CalculateShippingCost () {
    // do some lengthy calculation here and
    // calculate the shipping cost
    Console.WriteLine...

Filters


It often happens that we need to show filtered data. In this case, we can include logic in one of the functions in a service. However, this logic can get lost if a service has many methods. Similarly, we might have to format some data before showing it in the view. Angular introduces filters for precisely these things—either format the value of an expression for display or filter values from an array. Angular comes with some of the most common filters to format number, currency, or date. Refer to the built-in filters available at https://docs.angularjs.org/api/ng/filter.

Let's write a custom filter. In our previous example, our service returns some employees. Let's add a few more employees whose age is more than 58 years. Let's assume that the retirement age is 60 years, and anyone whose age is 58 years or more is about to retire. Then, let's filter the employees. So, here's the modified service:

'use strict';

app.service('employeeSvc', function () {

  var Employee = function (name...
Left arrow icon Right arrow icon

Description

This book helps beginner-level AngularJS developers organize AngularJS applications by discussing important AngularJS concepts and best practices. If you are an experienced AngularJS developer but haven't written directives or haven't created custom HTML controls before, then this book is ideal for you.

What you will learn

  • Experience the power of twoway data binding using AngularJS and threeway data binding using Firebase
  • Use dependency injection in AngularJS
  • Get the $http and $resource services to work with REST APIs
  • Realize the full power of AngularJS by writing custom elements, attributes, and so on, using directives
  • Create realtime apps using Firebase and AngularJS
  • Discover the benefits and uses of Node.js, Yeoman, Yo Angular generator, Grunt, and Bower
  • Get to grips with the basics of Git and use Git flow for a more productive Git branching workflow

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 28, 2015
Length: 156 pages
Edition : 1st
Language : English
ISBN-13 : 9781784394196
Vendor :
Google
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Apr 28, 2015
Length: 156 pages
Edition : 1st
Language : English
ISBN-13 : 9781784394196
Vendor :
Google
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 62.98
AngularJS Web application development Cookbook
€41.99
Data Oriented Development with Angularjs
€20.99
Total 62.98 Stars icon

Table of Contents

10 Chapters
1. AngularJS Rationale and Data Binding Chevron down icon Chevron up icon
2. Working with Data Chevron down icon Chevron up icon
3. Custom Controls Chevron down icon Chevron up icon
4. Firebase Chevron down icon Chevron up icon
5. Getting Started with AngularFire Chevron down icon Chevron up icon
6. Applied Angular and AngularFire Chevron down icon Chevron up icon
A. Yeoman Chevron down icon Chevron up icon
B. Git and Git Flow Chevron down icon Chevron up icon
C. Editors and IDEs Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5
(4 Ratings)
5 star 50%
4 star 50%
3 star 0%
2 star 0%
1 star 0%
T. Benjamin Jul 03, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If you are like many developers you've picked up a little bit of one framework or library and a little bit from others. The problem is that you haven't yet crossed the bridge into really getting deeply proficient in one framework. Angular is a case in point, at least for me. The initial entry point was fine, but I then hit their fabled jag into the more difficult parts and it slowed me down a lot. This book does a really good job in helping an intermediate developer get past the initial learning stage for Angular and into more constructive code. In particular, at least for me, it helped to get into writing directives, into seeing more into services/factories and most especially into seeing how data could be handled with Firebase.Firebase offers some intriguing advantages for the right kind of data. I mainly work with relational databases, so this part felt more like an example of how databases could be integrated. But, seeing how quickly data can be integrated with the Angular code and how three way data binding can be explored quickly has made me re-think the possible role of Firebase in a development stack.There are a few places where I felt that the material tried to reach too many audiences at the same time. The introductory material was fine, but not particularly new. Similarly, it was nice to have Yeoman and Git, along with editors covered in the Appendices. But I would have appreciated more information about data structures for Firebase and still more code examples about different types of applications and AngularFire. So, this book may not be right for you if you are trying to get from an intermediate stage to a more advanced stage. But for beginner/intermediate level programmers that want to get a clearer sense of how data can be handled in the Angular framework, this is really an excellent book.One note, really for all Angular books out at this writing, is going to be how they fare with Angular 2. Right now its too early to tell, but if you are looking at this book with a desire to learn Angular 2, make sure to check if the code has been updated. That's probably obvious, but seemed important to point out.So, in summary, if you know the basics of Angular, but haven't yet started to really write and understand directives and/or you want to get a better sense for how to handle noSQL like data stores with Angular, this is an excellent resource.
Amazon Verified review Amazon
David Nunez Jun 13, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Technologies like Firebase are very interesting as they signal a reduced role for server-side applications, as front-end fat clients can directly access data in many use cases. This isn't to say Firebase (a cloud service) offers no way for you to implement custom scripts (ie, for complicated non-OAuth authentication processes specific to your own company) or secure your data from unwanted access or rule out processing-intensive analytics performed by existing server side applications, it still allows for all of that. But where it really shines is by exposing your data via RESTful APIs (accessible by client or some analytics-heavy server side application) and also abstracting away the monotonous setups of data validation and authentication so you can focus on writing your front-end UI application (or server-side analytics tools in Node, Python, Java, Ruby, etc.). But the biggest draw to this technology right now might be the 3-way binding feature, where Firebase communicates data changes instantly via WebSocket technology to either your front-end clients or server-side applications. It's an exicting technology that has already scaled well to the most recent political elections in the U.K. (see Google I/O 2015 video on Firebase), and it could help shape the way NoSQL technologies and cloud services package products and features together for web developers and data scientists in the future.For the web developer needing the ability to rapidly prototype and deploy a new application in a framework like Angular, this book is a great tutorial and paints a solid picture of the intended workflow of front-end development with a relatively simple backend setup. Although the book is targeted mostly at beginner's I think it's a good refresher for seasoned Angular devs who need to familiarize themselves with "best practices" that will help them prepare for easier transitions to the newer versions of Angular on the horizon.One critique I've leveled against some Angular books published this year (like Brad Dayley's "Learning AngularJS") is they teach "last year's patterns". Front-end frameworks are going through some rapid shifts in the past year and will continue until much of the ES6 and Web Component heavy standards fully sink-in, so it's probably important right now for devs to be making whatever small or large steps towards those standards that they can afford for the time being. For devs new to Angular, I think it's severely unfair to offer them tutorials that teach them old patterns or lead them into "scope soup" traps that can befall Angular developers. So even some of the best Angular books to date (ie, Adam Freeman's "Pro AngularJS") have limited value now in prepping for the transition in JavaScript development. This book however, is current and thorough and in my opinion, now the best beginner's resource out there for new Angular devs.My only critique on this book is his coverage of the infamous "service vs factory" topic. He doesn't spend too long on the topic and although the piece he brought up contributes to the topic, it is insufficient alone to properly represent it. Although he's one of the few who actually make an Angular factory follow a true factory design pattern (amazing how common it's become in Angular development to make factories that don't create new instances of objects), he doesn't showcase newing-up Services and how to use prototypal inheritance in services to bring out some really useful featurues. Perhaps a couple more pages devoted to the topic would have been all that was needed.One reason this book is so valuable right now for beginner's is because the author links together old and new Angular patterns, so any new Angular dev can step into a company and know not only the better patterns going forward but also how to interpret the existing Angular codebase they're working in. For example, the controllerAs syntax is introduced later in the book, where its benefits can be more clearly showcased after having brought the reader through earlier, simpler examples without it. And that is perhaps what impressed me most about this book is the author's solid teaching style; he doesn't bludgeon the reader with a massive amount of complexity, nor does he rob them of the truly useful depth and detail they need to be proficient. You're introduced to concepts in small, usable pieces (which usually resemble the Angular 1.0 best practices) and then taught to refine them and shown why to do so later. And as each newer "best practice" is taught, he provides several solid references that if you explore them you'll find to be solid well-explained articles that can be useful if you find you have to justify yourself in a debate with a fellow dev over best practices.The book ramps up from Angular basics to Firebase basics and caps off with a final chapter that puts it all together into a very usable mock application. And to add on appendices that cover git (complete with resolving real world merge conflicts), dependency management through npm and bower, and I think you've got a tremendous resource for developers new to the open-source world who want to rapidly develop solid web applications.
Amazon Verified review Amazon
Anantha Narayanan Jul 06, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
For Javascript developers this book is a great utility to learn AngularJS. For those who are first timers in javascript/angular, learn the basics of the framework before buying this book.This book covers features of angularjs, getting data through ajax, creating your own muscle (directives), and firebase. Firebase is a NoSQL database which saves JSON data in it. This book gives decent introduction to it and tips on how to arrange your data model for efficient data retrieval.The book then talks about AngularFire, which is a plugin for angular to firebase. The book has covered a lot of topics but not a deeper analysis and understanding. But for beginners/intermediate learners this is far too much to know.
Amazon Verified review Amazon
Fernando Noronha Sep 26, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Escolhi este livro por causa dos exemplos com o firebase. Gostei muito e já coloquei em prática. É uma boa publicação para quem procura exemplos de como usar o angularjs integrado com o banco de dados firebase.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.

Modal Close icon
Modal Close icon