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:

Arrow left icon
Profile Icon Manoj Waikar
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5 (4 Ratings)
Paperback Apr 2015 156 pages 1st Edition
eBook
Mex$398.69 Mex$442.99
Paperback
Mex$553.99
Subscription
Free Trial
Arrow left icon
Profile Icon Manoj Waikar
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5 (4 Ratings)
Paperback Apr 2015 156 pages 1st Edition
eBook
Mex$398.69 Mex$442.99
Paperback
Mex$553.99
Subscription
Free Trial
eBook
Mex$398.69 Mex$442.99
Paperback
Mex$553.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781784398057
Vendor :
Google
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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 Mex$85 each
Feature tick icon Exclusive print discounts
$279.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 Mex$85 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Mex$ 1,682.98
AngularJS Web application development Cookbook
Mex$1128.99
Data Oriented Development with Angularjs
Mex$553.99
Total Mex$ 1,682.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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.

Modal Close icon
Modal Close icon