Angular Services

By Sohail Salehi
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Setting Up the Environment

About this book

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.

Publication date:
February 2017
Publisher
Packt
Pages
294
ISBN
9781785882616

 

Chapter 1.  Setting Up the Environment

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:

  • The foundation: Angular is introduced and supported by Google and targeted at evergreen modern browsers. This means that we, as developers, don't need to look out for hacky solutions in each browser upgrade anymore. The browser will always be updated to the latest version available, letting Angular worry about the new changes and leaving us out of it. This way, we can focus more on our development tasks.

  • The community: Think about the community as an asset; the bigger the community, the wider the range of solutions to a particular problem. Looking at the statistics, the Angular community is still way ahead of others, and the good news is that this community is leaning toward being more involved and contributing more on all levels.

  • The solution: If you look at the previous JS frameworks, you will see most of them focus on solving a problem for a browser first, and then for mobile devices. The argument for that could be simple--JS wasn't meant to be a language for mobile development. However, things have changed to a great extent over recent years and people now use mobile devices more than before. I personally believe that a complex native mobile application, which is implemented in Java or C, is more performant compared to its equivalent implemented in JS, but the thing here is that not every mobile application needs to be complex. So, business owners have started asking questions like "Why do I need a machine gun to kill a fly?"

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: 

  • First, we will learn about Angular and the main problem it solves

  • Then, we will talk a little bit about JavaScript history and the differences between Angular and AngularJS 1

  • Next we will introduce The Sherlock Project

  • Finally, we will install the tools and libraries we need to implement this project.

 

Introducing Angular


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.

 

There is no backward compatibility


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.

 

Previous knowledge of AngularJS 1.x is not necessary


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 relationship between ECMAScript, AtScript, and TypeScript


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.

Tip

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.

Note

For more details about JavaScript, ECMAScript, and how they evolved during the past decade, visit https://en.wikipedia.org/wiki/ECMAScript.

 

Setting up tools and getting started!


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/.

Tip

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.

 

Setting up the seed project


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:

  • Custom-made seeds usually come with a personal twist depending on the developers taste. Although sometimes it might be a great help, since we are going to build everything from scratch and learn the fundamental concepts, they are not favorable to our project.

  • The official seeds are usually minimal. They are very slim and don't contain an overwhelming amount of 3rd party packages and environmental configurations.

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.

 

Setting up an Angular project in WebStorm


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.

Tip

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 server 

Alternatively, 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:

Tip

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.

 

Frontend developers versus backend developers


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.

 

Introducing The Sherlock Project


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.

To achieve this goal, we will implement a couple of services and inject them to the project wherever they are needed. Each chapter will discuss one aspect of the project and will focus on one related service. At the end, all services will come together to act as one big project.

 

Summary


This chapter covered a brief introduction to Angular. We saw where Angular comes from, what problems it will solve, and how we can benefit from it.

We talked about the project that we will be creating with Angular. We also saw which other tools are needed for our project and how to install and configure them. Finally, we cloned an Angular seed project, installed all its dependencies, and started a web server to examine the application output in a browser.

In the next chapter, we will create all the required wireframes for this project and use them as a base structure for the rest of the book.

About the Author

  • Sohail Salehi

    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.

    Browse publications by this author

Recommended For You

Architecting Angular Applications with Redux, RxJS, and NgRx

Manage state in Angular to write high performing web apps by combining the power of Flux, RxJS, and NgRx

By Christoffer Noring
Angular Projects

Understand Angular web development by building real-world captivating applications exploring various web technologies and best practices

By Zama Khan Mohammed
Angular Router

From Angular core team member and creator of the router

By Victor Savkin
Angular for Enterprise-Ready Web Applications - Second Edition

Revised and updated second edition of the bestselling hands-on guide to building enterprise-ready web apps using an evergreen Angular platform

By Doguhan Uluca