Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Angular Services
Angular Services

Angular Services: -

eBook
$24.99 $35.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.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

Angular Services

Chapter 2.  Introducing Wire-Frames

In this chapter, we are going to create all wire-frames for this project. Each wire-frame here is a simple component and a template with minimum code. We are not going to create major business logic here. There are just blueprints to clarify the road map for this project. So wire-frames are the very basic foundations for the business logic that we are going to create and the layout that we are going to show to the user.

As we discuss the wire-frames and later implement them in the chapters to come, we will walk through the eight fundamental concepts in Angular in this chapter. These concepts are:

  • Modules
  • Components
  • Templates
  • Metadata
  • Data Binding
  • Directive
  • Services
  • Dependency Injection

What is a module?

The short answer is: every class you create in Angular is a module. The contents of a module could be anything. It could be a component, a service, a simple piece of data, and even they could be a library of other modules. They might look different, but they share one purpose: modules bring (export) one piece of functionality to the Angular projects.

Note

Creating Angular projects in a modular fashion makes the testing and maintenance tasks easy and helps the scalability in the future. However, you are not limited to an Angular modular approach and you can use your own style.

Later in this chapter, we will see that there is an export keyword in front of each class keyword:

export class MyClassName{} 

This is how Angular shares the logic inside that module (class) with the rest of the project. To use this module in other parts of a project, we just need to import it. Imagine the preceding code is saved inside a file named: myclassname.ts. To use that module in another module...

Components - the reusable objects

Components in Angular 2 are building blocks that address and provide solutions for different concerns in a web app. If we can solve one problem in one component, it means we can use that same component later in other parts of the current project or other projects. They are usually used to handle a part of a view (an HTML template). So if we create a component for a progress bar, we can use it later anywhere in the project where we need it. We can use components in other projects as well. For example, a component for a navigation bar that is created in one project, can be imported and be used in other projects in the future.

Components are basically nothing more than a class, with a bunch of methods, properties, and other usual codes. Inside the seed project that we set up in the previous chapter, open the src/app/about/about.ts file, and observe the code:

// src/app/about/about.ts 
import {Component} from '@angular/core'; 
@Component({ 
  selector...

The root component

In this book, we will have a couple of components and services that will work together to achieve a goal. But we need a root component to act as a communication center between all these players. This root component will control the application flow. Let's start by creating this component:

  1. Inside the WebStorm IDE, open the app.ts file, and notice the export line:
            export class AppComponent {} 
    
  2. As we saw before, the export keyword simply indicates that we are willing to share this class with every other player in the project. In other words, if anyone needs this class, they just need to import it in their own body.
  3. The plan is to make the AppComponent class as the root component for our project, that is why we have the Component function imported from the Angular2 core module:
            import {Component} from 'angular2/core'; 
            export class Sherlock {} 
    
  4. This code should be self...

Updating the Bootstrap file

Now before checking the results in the browser, there are a few updates that we need to do. First, open the app.modules.ts file inside the src/app folder and notice the import lines. The red color for the imported class means it does not exist:

        import {About} from './about/about'; 

That is right, because we removed all previous definitions in the seed project, so remove all troubled lines. That includes the following imports:

        import {About} from './about/about'; 
        import {Home} from './home/home'; 
        import {RepoBrowser} from './github/repo-browser/repo-browser'; 
        import {RepoList} from './github/repo-list/repo-list'; 
        import {RepoDetail} from './github/repo-detail/repo-detail'; 

Tip

Please notice that we don't need to mention...

What is a module?


The short answer is: every class you create in Angular is a module. The contents of a module could be anything. It could be a component, a service, a simple piece of data, and even they could be a library of other modules. They might look different, but they share one purpose: modules bring (export) one piece of functionality to the Angular projects.

Note

Creating Angular projects in a modular fashion makes the testing and maintenance tasks easy and helps the scalability in the future. However, you are not limited to an Angular modular approach and you can use your own style.

Later in this chapter, we will see that there is an export keyword in front of each class keyword:

export class MyClassName{} 

This is how Angular shares the logic inside that module (class) with the rest of the project. To use this module in other parts of a project, we just need to import it. Imagine the preceding code is saved inside a file named: myclassname.ts. To use that module in another module...

Components - the reusable objects


Components in Angular 2 are building blocks that address and provide solutions for different concerns in a web app. If we can solve one problem in one component, it means we can use that same component later in other parts of the current project or other projects. They are usually used to handle a part of a view (an HTML template). So if we create a component for a progress bar, we can use it later anywhere in the project where we need it. We can use components in other projects as well. For example, a component for a navigation bar that is created in one project, can be imported and be used in other projects in the future.

Components are basically nothing more than a class, with a bunch of methods, properties, and other usual codes. Inside the seed project that we set up in the previous chapter, open the src/app/about/about.ts file, and observe the code:

// src/app/about/about.ts 
import {Component} from '@angular/core'; 
@Component({ 
  selector: 'about...

The root component


In this book, we will have a couple of components and services that will work together to achieve a goal. But we need a root component to act as a communication center between all these players. This root component will control the application flow. Let's start by creating this component:

  1. Inside the WebStorm IDE, open the app.ts file, and notice the export line:

            export class AppComponent {} 
    
  2. As we saw before, the export keyword simply indicates that we are willing to share this class with every other player in the project. In other words, if anyone needs this class, they just need to import it in their own body.

  3. The plan is to make the AppComponent class as the root component for our project, that is why we have the Component function imported from the Angular2 core module:

            import {Component} from 'angular2/core'; 
            export class Sherlock {} 
    
  4. This code should be self explanatory. Normally each import command has two main parameters. First we need to mention...

Updating the Bootstrap file


Now before checking the results in the browser, there are a few updates that we need to do. First, open the app.modules.ts file inside the src/app folder and notice the import lines. The red color for the imported class means it does not exist:

        import {About} from './about/about'; 

That is right, because we removed all previous definitions in the seed project, so remove all troubled lines. That includes the following imports:

        import {About} from './about/about'; 
        import {Home} from './home/home'; 
        import {RepoBrowser} from './github/repo-browser/repo-browser'; 
        import {RepoList} from './github/repo-list/repo-list'; 
        import {RepoDetail} from './github/repo-detail/repo-detail'; 

Tip

Please notice that we don't need to mention the extension (.ts) for the file we are importing.

When you do so, the 'Declarations' start to complain. So remove all missing elements from that line, too. After all of these changes, the app.modules...

Running the web server


To see these updates in the browser, first run the web server in the background. Open a new terminal window - or use the embedded terminal in WebStorm IDE - and run the following command:

$ npm run server

It will take a few moments to build the app in the background and run the web server. Once the web server is up and running, open a browser window and visit the http://localhost:3000 .

Now if you inspect the code inside the browser, you will notice the new <app> tag in the page

Bootstrapping versus root component


You might ask why we need a bootstrap file to load the root component? Couldn't we have the root component in charge of loading everything itself? The answer is yes, we could. But, the good thing about having a bootstrap is better isolation, and as a result, better separation of concerns. Look at all those JavaScript files included in the index.html and compare it to the contents of app.html:

# index.html 
<!DOCTYPE html> 
<html> 
  <head> 
    <!-- head contents --> 
  </head> 
  <body> 
    <app> 
      Loading... 
    </app> 
    <script src="polyfills.bundle.js"></script> 
    <script src="vendor.bundle.js"></script> 
    <script src="app.bundle.js"></script> 
  </body> 
</html>  
 
# app/app.html 
<h1>The Sherlock Project</h1> 

Having a bootstrap in a project gives us more flexibility on the environmental and the browser settings and leaves the...

The big picture


Now that we have the root component in place, we can add all wire-frames for this project:

The Sherlock Project 
|- Collector 
|- Rating 
|- Notifier 
|- Evidence 
|- AI 
|- Report 
|- Autopilot 
'- Accuracy 

Each wire-frame introduced here represents one of the chapters for the remainder of this book. They will have different functionality, UI, inputs and outputs, but they will have one thing in common. The root Component - AppComponent - connects them all together and will be in charge of loading and navigating through the appropriate page.

Please keep in mind that what we will create here is just a simple blueprint for coming chapters, that's why we call them wire-frame. As we go through each chapter, we will take each of these wire-frames and enhance them by adding proper services, data, templates, and so on.

The navigation system


Before continuing to implement wire-frames, let's put the navigation system in place. For now we are going to create a navigation bar with options for Chapters 3 to 10. However, you might have noticed that Chapter 5, The Notifier Service – Creating Cron Jobs in Angular, needs a different type of UI and putting it inside a menu item doesn't make sense. That makes perfect sense, but for now we tend to keep things as simple as possible. The objective for assigning each chapter to a menu item is for easier demonstration only. Once we have all components, services, and their functionality in place, we can review the whole UI and modify it to a better one.

The Angular router module


All routing features in Angular 2 are available inside the angular2/router module. So if we load it inside the bootstrap-er we can access all of those features through any component in this project. The Angular 2 seed project has already provided the required configurations and we don't need to do anything. But to see how it is done, let's checkout the index.html file and follow the references over there. Open the index.html and notice the JavaScript files included there:

# index.html 
    <script src="polyfills.bundle.js"></script> 
    <script src="vendor.bundle.js"></script> 
    <script src="app.bundle.js"></script> 

The files we are interested in are vendor.bundle.js and app.bundle.js. It seems that they should be at the same place where index.html exists, but there is no sign of them.

We talked about what is happening here in Chapter 1,Setting Up the Environment. As a reminder, please keep in mind that .ts files should be...

The collector wire-frame


This application is about investigating articles and news and finding the truth about them. So as the very first step we need to find them. The Collector's task is to fetch original news or articles from the given sources and organize them based on our desired format. The news/articles source could be anything. It could be a plain URL, an XML file, or simply a keyword which we can search to find related news. That means the user interface for the Collector will contain a couple of input boxes to enter a URL, RSS feeds or trending keywords, and a submit button.

Depending on the entry, we need a logic (we will see it will be a service) which processes the request, fetches the contents, figures out the title, body, the news source and the URL for each content, and saves them into a database table for future usage. The following diagram describes the work-flow in the Collector:

The collector component

Looking at the preceding diagram, it indicates that we need a component...

Accessing a component via root


In order to use the collector component inside the root component (app.ts) we need to inform the root about it. So declare the CollectorComponent inside the app.modules.ts.

Tip

Notice that as soon as you add the CollectorComponent in the declarations array, WebStorm IDE imports the related class automatically.

If you are not using WebStorm, you need to manually import the collector.component.ts into the root otherwise you will get an error later:

// src/app/app.ts 
//... 
import {CollectorComponent}from "./collector/collector.component"; 
//... 

Also don't forget to declare the new component in the module file:

// src/app/app.modue.ts 
import {CollectorComponent} from "./collector/collector.component"; 
//... 
@NgModule({ 
  declarations: [AppComponent, NavigationComponent, CollectorComponent], 
  //... 
}) 
export class AppModule { 
} 

Now that we have the Collector component imported, we have access to its selector. To prove that, edit the app.html as follows...

The rating wire-frame


Collecting articles and news is not enough and we want to know which entry has the highest score for investigation. The question is how do we rate them and what measures and factors should we use in our rating mechanism.

Initially, we can come up with some basic rules. For example, if the source of the news or article is a well known news agency, we should give them a different rank compared to the articles coming from a personal web log. Or if the news title has some trending keywords - which we can find from Google Trends, for example - then we should give them a higher rank compared to general and bland titles.

Also the date of the entry matters, too. We don't want to waste our resources on investigating old news. So everything about an entry counts.

Once again, we will spend a whole chapter on dealing with all of these business rules. For now let's just create the Rating component and modify the root component so it can recognize it.

The rating component

Like before...

The notifier wire-frame


The Notifier is a little bit more sophisticated. It will use the Collector service to collect and the rating service to rate the collected items, and it does this job automatically in specific hours. It is like implementing a Linux cron job inside Angular.

Note

Please note we don't need the Collector and the Rating components for this wire-frame. Rather we need the mechanism that does the collecting and rating tasks. This situation should explain the difference between directives and components and the importance of each concept better. In Chapter 5, The Notifier Service- Creating Cron Jobs in Angular where we implement the service for this business logic - we will deal with the details of this requirement. There we will also discuss the dependency injection and child injectors in more details.

Let's say we want to be informed twice a day about all news which has a minimum rank of 8/10. Moreover, let's assume we want to be notified via e-mail and also we want to see...

Updating the navigation system


So far we have created one root component, three components for the wire-frames, and one component for navigation system. Now it is the right time to take hard coded values out of the root template and replace them with actual routes. We are going to put the Android router module in charge of updating the view based on the selected menu item.

Before changing anything, click on any link in the navigation bar and notice the "loading..." message. The current <a href="#"> in each menu item, refreshes the whole page and completely reloads index.html every time. This is not ideal. The goal is to update a specific area of the index page with the view of a component associated with the menu item.

Note

Applications that update only a specific part of a screen are called SPA (Single Page Application) and they are very efficient in terms of reducing loading time. All page contents will be loaded and cached once and later requesting any page will be done in the background...

Switching to SPA


To turn this application into an SPA, follow these steps:

  1. Open app.routes.ts, import all components, and then define routes for each component as follows:

            // src/app/app.routes.ts 
            import {Routes} from '@angular/router'; 
            import {CollectorComponent} from "./collector/collector.component"; 
            import {RatingComponent} from "./rating/rating.component"; 
            import {NotifierComponent} from "./notifier/notifier.component"; 
     
            export const rootRouterConfig: Routes = [ 
              {path: '', redirectTo: 'collector', pathMatch: 'full'}, 
              {path: 'collector', component: CollectorComponent}, 
              {path: 'rating', component: RatingComponent}, 
              {path: 'notifier', component: NotifierComponent} 
            ]; 
    

    Now notice the array of objects that were passed to the Routes variable. The first property is path: and it is indicating the URL that will be displayed in the browser address bar. The second property is the component...

The Evidence Tree Builder Wire-frame


As part of investigation, we need to collect the evidence related to the article of our interest. The tricky part is how much evidence are we willing to collect?

Search any keywords in Google and you will get zillions of results. Obviously we don't want to include all of them. We need a business rule to filter out the irrelevant results and choose - let's say - up to 10 relevant evidences for each main node and five evidences for each branch. It is totally up to us how deep we want that tree to be. But let's start simple and add more complexity to it as we proceed.

We need to persist the nodes and branches to the database, and before that we need to create a specific document that can handle all relevant evidence. These will all be defined as child services for this component.

The other important factor here is showing the results in an interactive way. All inspectors used to have an investigation board that they pinned the related photos, papers, and so...

The AI Wire-frame


This is the brain of our application. After all of the collecting, rating, and so on, it is time for decision making. We need an Artificial Intelligence mechanism to observe the inputs and find the answer to a question or simply make a statement for the provided news or article.

To find the answer, we can look into the evidence tree, and depending on the tree's depth, ask a couple of yes/no questions. Again, we need to define some business rules for our questions, and then weight the value of their answers.

To expand it a little more, imagine we have some news and we ask a fundamental question about it. Then we build an evidence tree with a three level depth. The number of evidence for the main node is 10 so we need to find out if each piece of evidence supports our question? (the answer is yes) Is it against our evidence? (which means the answer is no). Or is it neutral? Then we add the value of the answers (each yes has the value of +1, no = -1, and neutral answers are...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • - Leverage the latest Angular and ES2016 features to create services
  • - Integrate third-party libraries effectively and extend your app’s functionalities
  • - Implement a real-world case study from scratch and level up your Angular skills

Description

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.

Who is this book for?

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.

What you will learn

  • Things you will learn:
  • • Explore various features and topics
  • involved in modules, services, and
  • dependency injection
  • • Sketch and create wire-frames for
  • your project
  • • Use controllers to collect data and
  • populate them into NG UIs
  • • Create a controller and the required
  • directives to build a tree data
  • structure
  • • Implement a logic to decide the
  • relevancy of any given evidence
  • • Create a partially-AI service
  • • Build controllers to set the template
  • for the report
  • • Collect, investigate, perform decision making,
  • and generate reports in one
  • the big automated process

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 24, 2017
Length: 294 pages
Edition : 1st
Language : English
ISBN-13 : 9781785880483
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 : Feb 24, 2017
Length: 294 pages
Edition : 1st
Language : English
ISBN-13 : 9781785880483
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 $5 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 $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 98.98
Angular Services
$43.99
Angular 2 Cookbook
$54.99
Total $ 98.98 Stars icon
Banner background image

Table of Contents

8 Chapters
1. Setting Up the Environment Chevron down icon Chevron up icon
2. Introducing Wire-Frames Chevron down icon Chevron up icon
3. The Collector Service - Using Controllers to Collect Data Chevron down icon Chevron up icon
4. The Rating Service - Data Management Chevron down icon Chevron up icon
5. The Notifier Service - Creating Cron Jobs in Angular Chevron down icon Chevron up icon
6. The Evidence Tree Builder Service - Implementing the Business Logic Chevron down icon Chevron up icon
7. The Report Generator Service - Creating Controllers to Set Report Template Chevron down icon Chevron up icon
8. The Accuracy Manager Service - Putting It All Together Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
(1 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 100%
1 star 0%
Amazon Customer Apr 04, 2017
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
I am truely confuse. In chapter Components - the reusable objects, it ask me to delete all directories and files inside app/ folder. Then for the next couple chapters, it wants to look at files inside app. Where do I get those files from ????
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.