31,19 €
A primary concern with modern day applications is that they need to be dynamic, and for that, data access from the server side, data authentication, and security are very important. Angular leverages its services to create such state-of-the-art dynamic applications.
This book will help you create and design customized services, integrate them into your applications, import third-party plugins, and make your apps perform better and faster. This book starts with a basic rundown on how you can create your own Angular development environment compatible with v2 and v4. You will then use Bootstrap and Angular UI components to create pages. You will also understand how to use controllers to collect data and populate them into NG UIs.
Later, you will then create a rating service to evaluate entries and assign a score to them. Next, you will create "cron jobs" in NG. We will then create a crawler service to find all relevant resources regarding a selected headline and generate reports on it. Finally, you will create a service to manage accuracy and provide feedback about troubled areas in the app created.
This book is up to date for the 2.4 release and is compatible with the 4.0 release as well, and it does not have any code based on the beta or release candidates.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 317
Copyright © 2017 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: February 2017
Production reference: 1200217
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78588-261-6
www.packtpub.com
Author
Sohail Salehi
Copy Editor
Safis Editing
Reviewer
Phodal Huang
Project Coordinator
Devanshi Doshi
Commissioning Editor
Amarabha Banerjee
Proofreader
Safis Editing
Acquisition Editor
Larissa Pinto
Indexer
Mariammal Chettiyar
Content Development Editor
Samantha Gonsalves
Graphics
Jason Monteiro
Technical Editor
Anushree Arun Tendulkar
Production Coordinator
Shraddha Falebhai
Sohail Salehi is a veteran developer who recently decided to become a data scientist. He believes when you look at a programming challenge from a data scientist perspective, things started to change slightly and what used to be the ultimate solution, somehow morphs into a stepping stone for what really matters--data.
He won't lay down some tests and codes as soon as a programming challenge is handed to him, rather he has started to think WHY do we need to gather data, WHAT potential value is hidden inside this data and HOW to convert this potential into value that will make business thrive.
Although he has written a couple of other programming books before, The Sherlock Project is his first attempt to look at the programming challenge from a different perspective. This story is about discovering hidden values inside data and it is the project that he discusses in this book, Angular Services. In the past decade, he worked on some interesting projects with teams of bright developers. But challenges such as handling the traffic for a national newspaper website (NZ Herald) or creating a new game for Lotto (Lotto - 2nd Chance) are not attractive to him anymore. After he got his first certificate in Machine Learning from University of Washington, he decided to combine his development skills with new concepts that he is discovering in his new professional life and provide creative solutions for daily data-related challenges.
Technical concepts are not his only passion. He is an avid traveler and an adventurous surfer. Currently he lives in Bali, where the big waves are roaring most of the year, and he benefits from the rich Balinese culture and stunning tropical nature, which brings out the best of himself.
I would like to thank the Packt Publishing team for supporting me and giving me the opportunity to write and publish another book. My special thanks to Samantha Gonsalves, who helped me all the way and patiently directed me to the path and the goals we set for this book whenever I was off track.
Phodal Huang is a developer, creator, and author. He works for ThoughtWorks as a consultant. He currently focuses on IoT and frontend development. He is the author of Design Internet of Things and Growth: Thinking in Full Stack (in publishing) in Chinese.
He is an open source enthusiast, and has created a series of projects in GitHub. After daily work, he likes to reinvent some wheels for fun. He created the application Growth with Ionic 2 and Angular 2, which is about coaching newbies about programming. You can find out more wheels on his GitHub page, http://github.com/phodal.
He loves designing, writing, hacking, traveling, you can also find out more about him on his personal website at http://www.phodal.com.
He has reviewed Learning Internet of Things and Design IoT Projects.
For support files and downloads related to your book, please visit www.PacktPub.com.
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.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/Angular-Services/dp/1785882619.
If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
I always had a thing for the less traveled roads and it reflects itself in this book, Angular Services, as well. When it is about showing the power of front-end frameworks, there are tons of tutorials and contents on how to build To-Do list applications, or time trackers, or any other use cases and path ways which has been explored, explained and exhausted excessively.
What I've aimed for in this book is slightly different. Yes, the subject still Angular Services and we learn about all Angular framework features along the way, but the vehicle is a Machine Learning flavored application called 'The Sherlock Project' which explores:
What makes this book different is the use of Regression algorithm to explore major news agency outlets and other online resources, in order to get some insight about a news item. Basically we are using Angular Services as a host to several tools and concepts, so they work together and deliver four main tasks:
Perhaps that is the main reason that unlike other books, we didn't invest much efforts on how pretty our application looks, rather we focused on what it does and how unique it is. The code is open source and you are most welcome to take it to the next level by adding missing bits and pieces and decorating it with all the pretty bells and whistles that a front-end application deserves.
Chapter 1, Setting Up the Environment, tells you about what you need to get a basic Angular project up and running. The WebStorm IDE (offered by JetBrains) is free for non-commercial use and open source project. The official seed project (offered by Angular team) introduced in this chapter contains all the dependencies (Angular, TypeScript, WebPack and so on) plus the basic components to render a simple page.
Chapter 2, The Wire-Frames, demonstrates the road map we are going to explore for the rest of the book. It explains the components we are going to implement for this project and briefly introduces the services we are going to create to deliver the task of each remaining chapters.
Chapter 3, The Collector Service - Using Controllers to Collect Data, describes the basic Angular concepts like Components, data-binding, decorators and so on during implementation an HTTP service for hitting on RSS outputs and gathering some news. This is where Firebase Realtime Database will be introduced as well and we will see how to use it to record JSON objects as database entries.
Chapter 4, The Rating Service - Data Management, introduces the pipes for the first time and implements a sorting pipe for ordering data in a particular way. In this chapter, we will see how to use TypeScript classes not only to implement Components and Services, but also for creating business logic for models as well.
Chapter 5, The Notifier Service - Creating Cron Jobs in Angular, creates the logic for automated tasks. It will demonstrate a data flow which utilizes the services created in the previous chapters for collecting, rating, and storing qualified news in a list ready to be fetched and notified by the application or later via email. We will see how to implement the helper functions for calculating dates, finding out dated items, and keeping the database clean on each automated job cycle, as well.
Chapter 6, The Evidence Tree Builder Service - Implementing the Business Logic, presents the idea of gathering evidence which supports investigation for the article of our interest. We will study the ways we evaluate an article and how to measure, weigh down, and lift up the value of certain words in any article. We'll learn how to see an article as a bag of words and how to use this concept to calculate. Thus chapter also introduces two major libraries Google Custom Search Engine (CSE) and VisJS for data visualization.
Chapter 7, The Report Generator Service - Creating Controllers to Set Report Template, exposes the possible ways for implementing parent child interaction mechanisms where the child gets data models provided by the parent and fires back requests to the parent. We will learn how to implement components to read the result of previously saved data objects, parse them, and assemble new objects that can be used as building blocks of a report.
Chapter 8, The Accuracy Manager Service - Putting It All Together, implements the cure and prevention codes inside the application and save the programming resources by halting undesired situations. We will learn how to use global variables exported from the application module in order to store local variables and analyze their contents on demand.
A usual front-end development machine with basic hardware configuration, plus latest stable versions of NodeJS, WebStorm and official Angular seed project is all you need to follow along and implement the concepts introduced in each chapter. The seed project in chapter one, contains all you need to get started. Later in the following chapters, you will need a cloud account (Google account) to benefit from CSE (Custom Search Engine) and Firebase.
If you are a JavaScript developer who is moving on to Angular and have some experience in developing applications, then this book is for you. You need not have any knowledge of on Angular or its services.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, path names, dummy URLs, user input, and Twitter handles are shown as follows: "The next lines of code read the link and assign it to the to the BeautifulSoup function."
A block of code is set as follows:
#import packages into the project from bs4 import BeautifulSoup from urllib.request import urlopen import pandas as pdWhen we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
<head> <script src="d3.js" charset="utf-8"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head>When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: [default] exten => s,1,Dial(Zap/1|30) exten => s,2,Voicemail(u100) exten => s,102,Voicemail(b100) exten => i,1,Voicemail(s0) Any command-line input or output is written as follows:
C:\Python34\Scripts> pip install -upgrade pipC:\Python34\Scripts> pip install pandasNew terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "In order to download new modules, we will go to Files | Settings | Project Name | Project Interpreter."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Angular-Services. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/AngularServices_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
The two fundamental questions that one can ask when a new development tool is announced or launched are: how different is the new tool from other competitor tools and how enhanced is it when compared to its own previous versions? If we are going to invest our time in learning a new framework, common sense says we need to ensure that we get a good return on our investment. There are so many good articles out there about the pros and cons of each framework. To me, choosing Angular boils down to the following three aspects:
With that question in mind, Angular chose a different approach. It solves the performance challenges faced by mobile devices first. In other words, if your Angular application is fast enough on mobile environments, then it is lightning fast in the evergreen browsers.
So, that is what we will do in this chapter:
The previous JS frameworks we used had a fluid and easy workflow toward building web applications rapidly. However, as developers, what we are struggling with is technical debt.
In simple words, we could quickly build a web application with an impressive UI, but as the product kept growing and the change requests started kicking in, we had to deal with all maintenance nightmares that forced a long list of maintenance tasks and heavy costs to the business. Basically, the framework that used to be an amazing asset turned into a hairy liability (or technical debt if you like).
One of the major revamps in Angular is the removal of a lot of modules resulting in a lighter and faster core. For example, if you are coming from an Angular 1.x background and don't see $scope or $log in the new version, don't panic, they are still available to you via other means. There is no need to add overhead to the loading time if we are not going to use all the modules, so taking the modules out of the core results in a better performance.
So, to answer the question, one of the main issues Angular addresses is the performance issue. This is done through a lot of structural changes that we will get into over the course of the subsequent chapters.
To answer this heading, no, we don't have backward compatibility. If you have some Angular projects implemented with the previous version, depending on the complexity of the project, I wouldn't recommend migrating to the new version. Most likely, you will end up hammering a lot of changes into your migrated Angular project and in the end, you will realize it was more cost effective to just create a new project based on Angular from scratch.
Please keep in mind that the previous versions of Angular and Angular share a name, but they have huge differences in their nature and that is the price we pay for a better performance.
You might be wondering if you need to know AngularJS 1.x before diving into Angular. Absolutely not. To be more specific, it might be even better if you don't have any experience using Angular at all. This is because your mind wouldn't be preoccupied with obsolete rules and syntax. For example, we will see a lot of annotations in Angular that might make you uncomfortable if you come from an Angular 1 background. Also, there are different types of dependency injections and child injectors, which are totally new concepts introduced in Angular. Moreover, there are new features for templating and data binding, which help to improve loading time by asynchronous processing.
The current edition of ECMAScript (ES5) is the one that is widely accepted among all well-known browsers. You can think of it as the traditional JavaScript; whatever code is written in ES5 can be executed directly in the browsers. The problem is that most modern JavaScript frameworks contain features that require more than the traditional JavaScript capabilities. That is the reason ES6 was introduced. With this edition, and any future ECMAScript editions, we will be able to empower JavaScript with the features we need.
Now, the challenge is in running the new code in the current browsers. Most browsers nowadays recognize standard JavaScript codes only. So, we need a mediator to transform ES6 to ES5. That mediator is called a transpiler and the technical term for transformations is transpiling. There are many good transpilers out there and you are free to choose whatever you feel comfortable with.
Apart from TypeScript, you might want to consider Babel (babeljs.io) as your main transpiler.
Google originally planned to use AtScript to implement Angular; later they joined forces with Microsoft and introduced TypeScript as the official transpiler for Angular.
The following figure summarizes the relationship between various editions of ECMAScript, AtScript, and TypeScript.
For more details about JavaScript, ECMAScript, and how they evolved during the past decade, visit https://en.wikipedia.org/wiki/ECMAScript.
It is important to get the foundation right before installing anything else. Depending on your operating system, install Node.js and its package manager, npm. You can find a detailed installation manual on the Node.js official website, at https://nodejs.org/en/.
Ensure that both Node.js and npm are installed globally (they are accessible system wide) and have the right permissions.
At the time of writing this book, npm comes with Node.js out-of-the-box. However, in case their policy changes in the future, you can always download the npm and follow the installation process from https://npmjs.com.
The next stop would be the IDE; feel free to choose anything that you are comfortable with. Even a simple text editor will do. In this book, I will use WebStorm because of its embedded TypeScript syntax support and Angular features, which speeds up the development process. Moreover, it is lightweight enough to handle the project we are about to develop. You can download it from https://jetbrains.com/webstorm/download.
During the first few chapters, we will use simple objects and arrays as placeholders for the data. However, at some stage, we will need to persist the data in our application. This means we need a database. In this book we are going to use Firebase Realtime Database. It is a free NoSQL cloud database provided by Google which come with whatever we need from a real-time and secure database.
For now, just leave the database subject. You don't need to create any connections or database objects for the first few chapters. We will revisit this later in Chapter 4, The Rating Service - Data Management.
The final requirement to get started would be an Angular seed project to shape the initial structure of our project. If you look at the public source code repositories, you can find several versions of these seeds. I prefer the official one for the following two reasons:
Speaking about packages, you might be wondering what happened to the other JavaScript packages we needed for this application; we didn't install anything other than Node and NPM. The next section will answer this question.
Assuming that you installed WebStorm, fire the IDE and check out a new project from a Git repository.
Now, set the repository URL to https://github.com/angular/angular2-seed.git and save the project in a folder called the sherlock project, as shown:
Click on the Clone button and open the project in WebStorm. Next, click on the packages.json file and observe the dependencies. As you can see, this is a very lean seed with minimal configurations. It contains the Angular release candidate 2, plus the required modules to get the project up and running.
As you see in the following screenshot, apart from main Angular modules, we have the rxjs library, which is the Reactive eXtension for JS and we will use it for transforming, composing, and querying streams of data.
The first thing we need to do is install all the required dependencies defined inside the package.json file. Right-click on the file and select the run npm install option.
Please note installing packages using right-click and choosing the installation command is valid inside the IDE only. If you prefer to use the command line, simply use the following command: $ npm install
Installing the packages for the first time will take a while. In the meantime, explore the devDependencies section of package.json in the editor. As you see, we have all the required bells and whistles to run the project, including TypeScript and web server to start the development:
"devDependencies": { "awesome-typescript-loader": "~0.16.2", "es6-promise": "3.0.2", "es6-shim": "0.35.0", "reflect-metadata": "0.1.2", "source-map-loader": "^0.1.5", "typescript": "~1.8.9", "typings": "~1.0.3", "webpack": "^1.12.9", "webpack-dev-server": "^1.14.0", "webpack-merge": "^0.8.4" },We also have some nifty scripts defined inside package.json that automate useful processes. For example, to start a web server and see the seed in action, we can simply execute the following command in a terminal. (These scripts are shipped with the seed project and they are located inside the package.json file, under the script property. There is nothing special about them, they are just simple npm commands and you are more than welcome to add your commands if you like):
$ npm run serverAlternatively, we can right-click on the package.json file and select Show npm Scripts. This will open another side tab in WebStorm and show all the available scripts inside the current file:
Double-click on the start script and it will run the web server and load the seed application on port 3000. This means that if you visit http://localhost:3000 , you will see the seed application in your browser, as illustrated:
If you are wondering where the port number comes from, look into the package.json file and examine the server key under the scripts section:
"server": "webpack-dev-server --inline --colors --progress --display-error-details --display-cached --port 3000 --content-base src"
There is one more thing before we move on to the next topic. If you open any .ts file, WebStorm will ask you if you want it to transpile the code to JavaScript. If you say no once, it will never show up again.
In the following screenshot, below the tabs we can see the question (Compile TypeScript to JavaScript?) and possible answers (OK, No, Configure):
Choose No because we don't need WebStorm to transpile for us because the start script already contains a transpiler that takes care of all the transformations for us.
Recently, I had an interesting conversation with a couple of colleagues of mine, which is worth sharing here in this chapter. One of them is an avid frontend developer and the other is a seasoned backend developer. You guessed what I'm going to talk about--the debate between backend/frontend developers and who is better. We saw these kind of debates between backend and frontend people in development communities long enough.
However, the interesting thing, which, in my opinion, will show up more often in the next few months (years), is a fading border between the ends (frontend/backend).
It feels like the reason that some traditional frontend developers are holding up their guard against new changes in Angular is not just because the syntax has changed, thus causing a steep learning curve, but mostly because they now have to deal with concepts that have existed natively in backend development for many years. Hence, the reason that backend developers are becoming more open to the changes introduced in Angular is that these changes seem natural to them.
Annotations or child dependency injections, for example, is not a big deal to backenders as much as it bothers the frontenders. I won't be surprised to see a noticeable shift in both the camps in the years to come. Probably, we will see more backenders who are willing to use Angular as a good candidate for some, if not all, of their backend projects and probably we will see more frontenders taking object-oriented concepts and best practices more seriously. Given that JavaScript was originally a functional scripting language, they will probably try to catch up with the other camp as fast as they can.
There is no comparison here and I am not saying which camp has an advantage over the other one. My point is, before modern frontend frameworks, JavaScript was open to be used in a quick and dirty inline script to solve problems quickly.
While this is a very convenient approach, it causes serious problems when you want to scale a web application. Imagine the time and effort you might have to make finding all of those dependent codes and refactoring them to reflect the required changes.
When it comes to scalability, we need a full separation between layers and that requires developers to move away from traditional JavaScript and embrace more OOP best practices in their day-to-day development tasks.
That's what has been practiced in all modern frontend frameworks and Angular takes it to the next level by completely restructuring the model-view-* concept and opening doors to the future features, which will eventually be a native part of any web browser.
During the course of this journey, we will dive into all new Angular concepts by implementing a semi-AI project, called The Sherlock Project.
This project will basically be about collecting facts, evaluating and ranking them, and making a decision about how truthful they are.