AngularJS Services Design, build, and test services to create a solid foundation for your AngularJS applications Jim Lavin BIRMINGHAM - MUMBAI AngularJS Services Copyright © 2014 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: August 2014 Production reference: 1140814 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78398-356-8 www.packtpub.com Cover image by Ádám Plézer ([email protected]) Credits Author Project Coordinator Jim Lavin Neha Bhatnagar Reviewers Proofreaders Ruy Adorno Maria Gould Mike McElroy Ameesha Green JD Smith Indexer Tejal Soni Acquisition Editor Joanne Fitzpatrick Production Coordinators Melwyn D'sa Content Development Editor Anila Vincent Alwin Roy Technical Editors Cover Work Pankaj Kadam Melwyn D'sa Aman Preet Singh Copy Editors Janbal Dharmaraj Karuna Narayanan Alfida Paiva About the Author Jim Lavin has been involved in software development for the past 30 years. He is currently the CTO for one of the leading service providers of online ordering for restaurants where his team uses AngularJS as a core part of their service offerings. He is the coordinator of the Dallas/Fort Worth area's AngularJS meetup group, and routinely gives presentations on AngularJS to other technology groups in the Dallas/Fort Worth area. I'd like to acknowledge all the people who have provided the inspiration and support that made this book a reality. To my father and mother, who taught me that there are no limitations in life, and that you can do anything as long as you are willing to put in the concentration and hard work to see it to the end. To my daughter, who would always help me get off the fence and make a decision by saying, "That sounds cool! Go for it!" To my team at work, who embraced the notion of rewriting our application with AngularJS with such enthusiasm that we did the impossible in a matter of months. And finally, to the AngularJS community, which has been a great part of my inspiration since I've adopted AngularJS. All their blog posts, videos, questions, and answers have helped to accelerate the adoption of AngularJS at an amazing rate, making me proud to be a part of their growing community. About the Reviewers Ruy Adorno is a senior front-end developer with more than 10 years of experience working in web development, application interfaces, and user experience. You can get to know more about him on his personal website http://ruyadorno.com. Mike McElroy is a longtime fan, booster, and contributor to the AngularJS community. He originally met the author through the AngularJS community on Google+ while doing a series of hangouts on AngularJS. He worked with AngularJS professionally, shortly after it emerged from the beta period, and has continued to be involved in the community to this day. He currently works for DataStax, developing the UI for their OpsCenter product, and lives in Columbus, Ohio, with his wife and menagerie of animals. JD Smith is a front-end architect with 15 years of consulting experience, ranging from small businesses to Fortune 500 companies. He enjoys working on large JavaScript applications and coming up with innovative improvements. In addition to consulting work, he runs a boutique staffing firm, UI Pros, with the goal of matching the best developers to the best jobs. Contact him at www.uipros. com or send an e-mail to [email protected]. www.PacktPub.com Support files, eBooks, discount offers, and more You might want to visit www.PacktPub.com for support files and downloads related to your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. TM http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. Why subscribe? • Fully searchable across every book published by Packt • Copy and paste, print and bookmark content • On demand and accessible via web browser Free access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access. Table of Contents Preface 1 Chapter 1: The Need for Services 7 AngularJS best practices 8 Responsibilities of controllers 8 Responsibilities of directives 9 Responsibilities of services 10 Summary 11 Chapter 2: Designing Services 13 Measure twice, and cut once 13 Defining your service's interface 13 Focus on the developer, not yourself 14 Favor readability over brevity 14 Limit services to a single area of responsibility 14 Keep method naming consistent 15 Keep to the top usage scenarios 15 Do one thing only 15 Document your interface 15 Designing for testability 16 Law of Demeter 16 Pass in required dependencies 17 Limiting constructors to assignments 20 Use promises sparingly 21 Services, factories, and providers 22 Structuring your service in code 28 Configuring your service 31 Summary 32 Table of Contents Chapter 3: Testing Services 33 The basics of a test scenario 33 Loading your modules in a scenario 35 Mocking data 36 Mocking services 38 Mocking services with Jasmine spies 40 Handling dependencies that return promises 42 Mocking backend communications 45 Mocking timers 47 Summary 48 Chapter 4: Handling Cross-cutting Concerns 49 Communicating with your service's consumers using patterns 49 Managing user notifications 54 Logging application analytics and errors 61 Authentication using OAuth 2.0 66 Summary 69 Chapter 5: Data Management 71 Models provide the state and business logic 71 Implementing a CRUD data service 75 Caching data to reduce network traffic 79 Transforming data in the service 82 Summary 87 Chapter 6: Mashing in External Services 89 Storing events with Google Calendar 89 Using Google Tasks to build a brewing task list 94 Tying the Google Calendar and task list together 98 Summary 105 Chapter 7: Implementing the Business Logic 107 Encapsulating business logic in models 108 Encapsulating business logic in services 111 Models or services, which one to use? 113 Controlling a view flow with a state machine 114 Validating complex data with a rules engine 120 Summary 123 Chapter 8: Putting It All Together 125 Wiring in authentication 126 Displaying notifications and errors 126 Controlling the application flow 127 [ ii ] Table of Contents Displaying data from external services 128 Building and calculating the recipe 130 Messaging is the heart of the application 132 Summary 132 Index 135 [ iii ]